React hooks updating array is not working - javascript

I'm currently learning hook, and I'm writing a todo-list:
import './App.css';
import React, {useState} from 'react';
import Item from './components/Item';
function App() {
const [tasks, setTasks] = useState([]);
const addTask = (e) => {
if(e.key === 'Enter'){
let newTask = {content: e.target.value, completed: false};
console.log(newTask);
setTasks(prevTask => {
return ([...prevTask, newTask]);
});
console.log(tasks);
}
}
const completeTask = (e) =>{
let newTask = tasks.slice();
newTask[e].completed = !tasks[e].completed;
setTasks(newTask);
}
const deleteTask = (e) => {
let newTask = tasks.slice();
newTask.splice(e);
setTasks(newTask);
}
return (
<>
<header className="todo-app__header">
<h1 className="todo-app__title">todos</h1>
</header>
<section className="todo-app__main">
<input className="todo-app__input" placeholder="What needs to be done?" onKeyDown={addTask}/>
<ul className="todo-app__list" id="todo-list">
{tasks.map(item => <Item num = {tasks.indexOf(item)} text={item.content} completed = {item.completed}
onClick = {completeTask(tasks.indexOf(item))} delete = {deleteTask(tasks.indexOf(item))}/>)}
</ul>
</section>
</>
);
}
export default App;
However, adding tasks is not working!!
The newTask printed is well, but it doesn't push into the tasks array.
The tasks is still empty.
What's the problem?
Also, another problem: is it related to useeffect? I don't know what useeffect is used for.

The issue is that every time your component renders, it executes both completeTask and deleteTask, because you are using function calls as props. You need to be passing in a function object or expression. Instead of telling the component to execute completeTask on click, the function call just executes it right there as soon as the component is rendered.
The problem is with this part of your code:
<ul className="todo-app__list" id="todo-list">
{tasks.map(item => <Item num = {tasks.indexOf(item)} text={item.content} completed = {item.completed}
onClick = {completeTask(tasks.indexOf(item))} delete = {deleteTask(tasks.indexOf(item))}/>)}
</ul>
The following lines:
delete = {deleteTask(tasks.indexOf(item))}
onClick = {completeTask(tasks.indexOf(item))}
Should be changed to:
delete = {() => deleteTask(tasks.indexOf(item))}
onClick = {() => completeTask(tasks.indexOf(item))}
In normal HTML, it would look like delete="deleteFunction()", but in React, it should be delete={deleteFunction}, because writing a function with parenthesis after it is a function call, not a function expression. If you need to pass in an argument, you can either pass the argument in as a prop on the component, or change the line to delete={() => deleteFunction(arg)}, as the parenthesis and arrow makes it a function expression.
See Handling Events: https://reactjs.org/docs/handling-events.html

Your code works well and there is no problem.
React setState action in async. Try to log it in useEffect.
const App = () = => {
const [tasks, setTasks] = useState([]);
useEffect(() => {
console.log(tasks)
}, [tasks]);
const addTask = () => {
const newTask = {...};
setTasks([...tasks, newTask]);
}
}
useEffect Docs

Here as I can see, you are doing console.log(tasks) in the same function.
Try the console.log(tasks) outside function and you will see tasks array with the values you entered.

there is no problem
import React, {useState} from 'react';
function Add() {
const [tasks, setTasks] = useState([]);
const addTask = (e) => {
if(e.key === 'Enter'){
let newTask = {content: e.target.value, completed: false};
console.log(newTask);
setTasks(prevTask => {
return ([...prevTask, newTask])
});
console.log(tasks);
}
}
const completeTask = (e) =>{
let newTask = tasks.slice();
newTask[e].completed = !tasks[e].completed;
setTasks(newTask);
}
const deleteTask = (e) => {
let newTask = tasks.slice();
newTask.splice(e);
setTasks(newTask);
}
return (
<>
<header className="todo-app__header">
<h1 className="todo-app__title">todos</h1>
</header>
<section className="todo-app__main">
<input className="todo-app__input" placeholder="What needs to be done?" onKeyDown={addTask}/>
<ul className="todo-app__list" id="todo-list">
{tasks.map((item)=> <li>{item.content}</li>)}
</ul>
</section>
</>
);
}
export default Add;
it works very well and that means your Item component is your problem.

Related

Updating react component

I have this piece of code:
let columnChooser = [productName]
function replacer (key: any) {
if (key == 1) {
message.info(`Click on item ${key}`);
columnChooser.push(productPrice)
}
}
what I want basically is to add productPrice into the existing array. With this method in my react return Ido not get a new column productPrice, I constantly have only productName. the function is from the drop-down menu and it grabs key values so an appropriate column can be added to the array.
Can anyone provide me with some insight into why this is not working
after function is run via button press I expected that new value be added into array and shown in front end
I couldn't quite understand your end goal, but from what I understand you want to update the value in a component. For that you can use the useState of React Hooks and the click event of the button.
example: https://codesandbox.io/s/6vryxv96pz
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const App = () => {
const [value, setValue] = useState("");
const [list, setList] = useState(["a", "b", "c"]);
const onChangeValue = (event) => {
setValue(event.target.value);
};
const onAddItem = () => {
setList((prevState) => {
const list = [...prevState, value];
return list;
});
setValue("");
};
return (
<div>
<ul>
{list.map((item, i) => (
<li key={i}>
<div>{item}</div>
</li>
))}
</ul>
<input type="text" value={value} onChange={onChangeValue} />
<button type="button" onClick={onAddItem} disabled={!value}>
Add
</button>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
in this case you need to use useState. Then your code would look like this:
// let columnChooser = [productName]
const [columnChooser, setColumnChooser] = useState ([productName]);
function replacer (key: any) {
if (key == 1) {
message.info(`Click on item ${key}`);
setColumnChooser(prevState => [...prevState, productPrice]);
// columnChooser.push(productPrice)
}
}

UseEffect runs on first render without being called using Context [duplicate]

According to the docs:
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
We can use the new useEffect() hook to simulate componentDidUpdate(), but it seems like useEffect() is being ran after every render, even the first time. How do I get it to not run on initial render?
As you can see in the example below, componentDidUpdateFunction is printed during the initial render but componentDidUpdateClass was not printed during the initial render.
function ComponentDidUpdateFunction() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
class ComponentDidUpdateClass extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidUpdate() {
console.log("componentDidUpdateClass");
}
render() {
return (
<div>
<p>componentDidUpdateClass: {this.state.count} times</p>
<button
onClick={() => {
this.setState({ count: this.state.count + 1 });
}}
>
Click Me
</button>
</div>
);
}
}
ReactDOM.render(
<div>
<ComponentDidUpdateFunction />
<ComponentDidUpdateClass />
</div>,
document.querySelector("#app")
);
<script src="https://unpkg.com/react#16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
We can use the useRef hook to store any mutable value we like, so we could use that to keep track of if it's the first time the useEffect function is being run.
If we want the effect to run in the same phase that componentDidUpdate does, we can use useLayoutEffect instead.
Example
const { useState, useRef, useLayoutEffect } = React;
function ComponentDidUpdateFunction() {
const [count, setCount] = useState(0);
const firstUpdate = useRef(true);
useLayoutEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<ComponentDidUpdateFunction />,
document.getElementById("app")
);
<script src="https://unpkg.com/react#16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
You can turn it into custom hooks, like so:
import React, { useEffect, useRef } from 'react';
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
if (didMount.current) func();
else didMount.current = true;
}, deps);
}
export default useDidMountEffect;
Usage example:
import React, { useState, useEffect } from 'react';
import useDidMountEffect from '../path/to/useDidMountEffect';
const MyComponent = (props) => {
const [state, setState] = useState({
key: false
});
useEffect(() => {
// you know what is this, don't you?
}, []);
useDidMountEffect(() => {
// react please run me if 'key' changes, but not on initial render
}, [state.key]);
return (
<div>
...
</div>
);
}
// ...
I made a simple useFirstRender hook to handle cases like focussing a form input:
import { useRef, useEffect } from 'react';
export function useFirstRender() {
const firstRender = useRef(true);
useEffect(() => {
firstRender.current = false;
}, []);
return firstRender.current;
}
It starts out as true, then switches to false in the useEffect, which only runs once, and never again.
In your component, use it:
const firstRender = useFirstRender();
const phoneNumberRef = useRef(null);
useEffect(() => {
if (firstRender || errors.phoneNumber) {
phoneNumberRef.current.focus();
}
}, [firstRender, errors.phoneNumber]);
For your case, you would just use if (!firstRender) { ....
Same approach as Tholle's answer, but using useState instead of useRef.
const [skipCount, setSkipCount] = useState(true);
...
useEffect(() => {
if (skipCount) setSkipCount(false);
if (!skipCount) runYourFunction();
}, [dependencies])
EDIT
While this also works, it involves updating state which will cause your component to re-render. If all your component's useEffect calls (and also all of its children's) have a dependency array, this doesn't matter. But keep in mind that any useEffect without a dependency array (useEffect(() => {...}) will be run again.
Using and updating useRef will not cause any re-renders.
#ravi, yours doesn't call the passed-in unmount function. Here's a version that's a little more complete:
/**
* Identical to React.useEffect, except that it never runs on mount. This is
* the equivalent of the componentDidUpdate lifecycle function.
*
* #param {function:function} effect - A useEffect effect.
* #param {array} [dependencies] - useEffect dependency list.
*/
export const useEffectExceptOnMount = (effect, dependencies) => {
const mounted = React.useRef(false);
React.useEffect(() => {
if (mounted.current) {
const unmount = effect();
return () => unmount && unmount();
} else {
mounted.current = true;
}
}, dependencies);
// Reset on unmount for the next mount.
React.useEffect(() => {
return () => mounted.current = false;
}, []);
};
a simple way is to create a let, out of your component and set in to true.
then say if its true set it to false then return (stop) the useEffect function
like that:
import { useEffect} from 'react';
//your let must be out of component to avoid re-evaluation
let isFirst = true
function App() {
useEffect(() => {
if(isFirst){
isFirst = false
return
}
//your code that don't want to execute at first time
},[])
return (
<div>
<p>its simple huh...</p>
</div>
);
}
its Similar to #Carmine Tambasciabs solution but without using state :)
‍‍‍‍‍‍
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
function useEffectAfterMount(effect, deps) {
const isMounted = useRef(false);
useEffect(() => {
if (isMounted.current) return effect();
else isMounted.current = true;
}, deps);
// reset on unmount; in React 18, components can mount again
useEffect(() => {
isMounted.current = false;
});
}
We need to return what comes back from effect(), because it might be a cleanup function. But we don't need to determine if it is or not. Just pass it on and let useEffect figure it out.
In an earlier version of this post I said resetting the ref (isMounted.current = false) wasn't necessary. But in React 18 it is, because components can remount with their previous state (thanks #Whatabrain).
I thought creating a custom hook would be overkill and I didn't want to muddle my component's readability by using the useLayoutEffect hook for something unrelated to layouts, so, in my case, I simply checked to see if the value of my stateful variable selectedItem that triggers the useEffect callback is its original value in order to determine if it's the initial render:
export default function MyComponent(props) {
const [selectedItem, setSelectedItem] = useState(null);
useEffect(() => {
if(!selectedItem) return; // If selected item is its initial value (null), don't continue
//... This will not happen on initial render
}, [selectedItem]);
// ...
}
This is the best implementation I've created so far using typescript. Basically, the idea is the same, using the Ref but I'm also considering the callback returned by useEffect to perform cleanup on component unmount.
import {
useRef,
EffectCallback,
DependencyList,
useEffect
} from 'react';
/**
* #param effect
* #param dependencies
*
*/
export default function useNoInitialEffect(
effect: EffectCallback,
dependencies?: DependencyList
) {
//Preserving the true by default as initial render cycle
const initialRender = useRef(true);
useEffect(() => {
let effectReturns: void | (() => void) = () => {};
// Updating the ref to false on the first render, causing
// subsequent render to execute the effect
if (initialRender.current) {
initialRender.current = false;
} else {
effectReturns = effect();
}
// Preserving and allowing the Destructor returned by the effect
// to execute on component unmount and perform cleanup if
// required.
if (effectReturns && typeof effectReturns === 'function') {
return effectReturns;
}
return undefined;
}, dependencies);
}
You can simply use it, as usual as you use the useEffect hook but this time, it won't run on the initial render. Here is how you can use this hook.
useNoInitialEffect(() => {
// perform something, returning callback is supported
}, [a, b]);
If you use ESLint and want to use the react-hooks/exhaustive-deps rule for this custom hook:
{
"rules": {
// ...
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "useNoInitialEffect"
}]
}
}
#MehdiDehghani, your solution work perfectly fine, one addition you have to do is on unmount, reset the didMount.current value to false. When to try to use this custom hook somewhere else, you don't get cache value.
import React, { useEffect, useRef } from 'react';
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
let unmount;
if (didMount.current) unmount = func();
else didMount.current = true;
return () => {
didMount.current = false;
unmount && unmount();
}
}, deps);
}
export default useDidMountEffect;
Simplified implementation
import { useRef, useEffect } from 'react';
function MyComp(props) {
const firstRender = useRef(true);
useEffect(() => {
if (firstRender.current) {
firstRender.current = false;
} else {
myProp = 'some val';
};
}, [props.myProp])
return (
<div>
...
</div>
)
}
You can use custom hook to run use effect after mount.
const useEffectAfterMount = (cb, dependencies) => {
const mounted = useRef(true);
useEffect(() => {
if (!mounted.current) {
return cb();
}
mounted.current = false;
}, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
};
Here is the typescript version:
const useEffectAfterMount = (cb: EffectCallback, dependencies: DependencyList | undefined) => {
const mounted = useRef(true);
useEffect(() => {
if (!mounted.current) {
return cb();
}
mounted.current = false;
}, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
};
For people who are having trouble with React 18 strict mode calling the useeffect on the initial render twice, try this:
// The init variable is necessary if your state is an object/array, because the == operator compares the references, not the actual values.
const init = [];
const [state, setState] = useState(init);
const dummyState = useRef(init);
useEffect(() => {
// Compare the old state with the new state
if (dummyState.current == state) {
// This means that the component is mounting
} else {
// This means that the component updated.
dummyState.current = state;
}
}, [state]);
Works in development mode...
function App() {
const init = [];
const [state, setState] = React.useState(init);
const dummyState = React.useRef(init);
React.useEffect(() => {
if (dummyState.current == state) {
console.log('mount');
} else {
console.log('update');
dummyState.current = state;
}
}, [state]);
return (
<button onClick={() => setState([...state, Math.random()])}>Update state </button>
);
}
ReactDOM.createRoot(document.getElementById("app")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
And in production.
function App() {
const init = [];
const [state, setState] = React.useState(init);
const dummyState = React.useRef(init);
React.useEffect(() => {
if (dummyState.current == state) {
console.log('mount');
} else {
console.log('update');
dummyState.current = state;
}
}, [state]);
return (
<button onClick={() => setState([...state, Math.random()])}>Update state </button>
);
}
ReactDOM.createRoot(document.getElementById("app")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
<div id="app"></div>
If you want to skip the first render, you can create a state "firstRenderDone" and set it to true in the useEffect with empty dependecy list (that works like a didMount). Then, in your other useEffect, you can check if the first render was already done before doing something.
const [firstRenderDone, setFirstRenderDone] = useState(false);
//useEffect with empty dependecy list (that works like a componentDidMount)
useEffect(() => {
setFirstRenderDone(true);
}, []);
// your other useEffect (that works as componetDidUpdate)
useEffect(() => {
if(firstRenderDone){
console.log("componentDidUpdateFunction");
}
}, [firstRenderDone]);
All previous are good, but this can be achieved in a simplier way considering that the action in useEffect can be "skipped" placing an if condition(or any other ) that is basically not run first time, and still with the dependency.
For example I had the case of :
Load data from an API but my title has to be "Loading" till the date were not there, so I have an array, tours that is empty at beginning and show the text "Showing"
Have a component rendered with different information from those API.
The user can delete one by one those info, even all making the tour array empty again as the beginning but this time the API fetch is been already done
Once the tour list is empty by deleting then show another title.
so my "solution" was to create another useState to create a boolean value that change only after the data fetch making another condition in useEffect true in order to run another function that also depend on the tour length.
useEffect(() => {
if (isTitle) {
changeTitle(newTitle)
}else{
isSetTitle(true)
}
}, [tours])
here my App.js
import React, { useState, useEffect } from 'react'
import Loading from './Loading'
import Tours from './Tours'
const url = 'API url'
let newTours
function App() {
const [loading, setLoading ] = useState(true)
const [tours, setTours] = useState([])
const [isTitle, isSetTitle] = useState(false)
const [title, setTitle] = useState("Our Tours")
const newTitle = "Tours are empty"
const removeTours = (id) => {
newTours = tours.filter(tour => ( tour.id !== id))
return setTours(newTours)
}
const changeTitle = (title) =>{
if(tours.length === 0 && loading === false){
setTitle(title)
}
}
const fetchTours = async () => {
setLoading(true)
try {
const response = await fetch(url)
const tours = await response.json()
setLoading(false)
setTours(tours)
}catch(error) {
setLoading(false)
console.log(error)
}
}
useEffect(()=>{
fetchTours()
},[])
useEffect(() => {
if (isTitle) {
changeTitle(newTitle)
}else{
isSetTitle(true)
}
}, [tours])
if(loading){
return (
<main>
<Loading />
</main>
)
}else{
return (
<main>
<Tours tours={tours} title={title} changeTitle={changeTitle}
removeTours={removeTours} />
</main>
)
}
}
export default App
const [dojob, setDojob] = useState(false);
yourfunction(){
setDojob(true);
}
useEffect(()=>{
if(dojob){
yourfunction();
setDojob(false);
}
},[dojob]);

How to pass not exported function from App to child component

I created a myFunction in my App.tsx, that refers to some states defined also in App. I need to be able to pass that function to my child component.
App.tsx
const [cartItems, setCartItems] = useState([] as CartItemType[]);
const { data, isLoading, error } = useQuery<CartItemType[]>(
'products',
getProducts
);
const [itemColor, setItemColor] = useState([]);
function myFunction(e) {
e.preventDefault();
let newData: any[] = [...data!];
let changedItem = {
...data!.find((i) => i.name === selectedData.name),
};
let changedItemIndex = data!.findIndex(
(i) => i.name === selectedData.name
);
changedItem.chair!.selected = e.target.value;
newData[changedItemIndex] = changedItem;
setItemColor(newData[0]);
}
Child.tsx
import myFunction from '../App';
<Item click={myFunction()}></Item>
Unfortunately that does not work. I also tried to do it through props, but also unsuccessfully.
Component Item its just exported function from Child.tsx to keep my code cleaner.
function Item(props) {
let colorHeaderClassName = `selected ${props.click}`;
return (
<>
<Button
onClick={props.click}
className={colorHeaderClassName}
/>
</>
);
}
export function myFunction(e) {
.....
.....
}
import {myFunction} from '../App';

I am trying to update the state using the React useState hook?? The Create Read and Delete part has been done but iam not able to update

I am making a To Do App using useState react hook.
I have complete with Create Read and Delete parts but
I have not been able to update the state.
Can somebody please help me.
I have complete the same with Class component.
/****************************** MY app.js file ********************************************/
import React, { useState } from "react";
import "./App.css";
import ToDoList from "./Components/ToDoList";
function App() {
const [change, handleChange] = useState("");
const [items, addItem] = useState([]);
let handleSubmit = (e) => {
e.preventDefault();
// console.log(change)
if (change !== "") {
addItem([...items, { text: change, key: Date.now() }]);
handleChange("");
}
};
let removeTask = (key) => {
let item = items.filter((ele) => {
return ele.key !== key;
});
console.log(item);
addItem([...item]);
};
let updateToDo = (value, key) => { // <<<<<<< I need to make changes in this piece of code.
let allItem = items.map((e) => {
if (e.key === key) {
e.text = value;
}
console.log(...allItem);
// addItem([...items, { allItem }]);
});
};
return (
<div className="toDoContainer">
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => handleChange(e.target.value)}
value={change}
placeholder="Add Item"
/>
<button>Add Item</button>
</form>
<ToDoList items={items} removeTask={removeTask} updateToDo={updateToDo} />
</div>
);
}
export default App;
/*************************************** My ToDoList.js *************************************/
import React from "react";
import "./ToDoList.css";
function ToDoList({ items, removeTask, updateToDo }) {
let toDoItems = items.map((item) => {
return (
<div className="toDoItems" key={item.key}>
<p>
<input
type="text"
id = {item.key}
value={item.text}
onChange={(e) => updateToDo(e.target.value, item.key)}
/>
<span onClick={() => removeTask(item.key)}>✘</span>
</p>
</div>
);
});
return <div>{toDoItems}</div>;
}
export default ToDoList;
You can map items into new array and when the item key matches the key parameter update the text property.
let updateToDo = (value, key) => {
const allItem = items.map(item => {
const newItem = {...item};
if (item.key === key) {
newItem.text = value;
}
return newItem;
});
console.log(...allItem);
addItem(allItem);
};
buddy!
First fo all, I suggest you can read document about React Hooks, it have clear explain how to update State when you using useState, I split several parts below:
On here const [items, addItem] = useState([]);, The Hooks useState will return a array, the first item is your value of state, at this time is a empty array [], the second item is a method which can update value of state.
Next, in your update method updateToDo, you used map to update original value of state and create the new value of state. so why didn't you call addItem to update your value of state?(Maybe you tried, but I have no idea for why you comment out that line?)
You just need to pass new value of state for addItem, and I suggest you can rename it to setItem instead of addItem.
You can following:
let updateToDo = (value, key) => { // <<<<<<< I need to make changes in this piece of code.
let allItem = items.map((e) => {
if (e.key === key) {
e.text = value;
}
addItem(allItem);
});
};

Using React useEffect hook with rxjs mergeMap operator

I'm trying to implement a data stream that has to use inner observables, where I use one from mergeMap, concatMap etc.
e.g.:
const output$$ = input$$.pipe(
mergeMap(str => of(str).pipe(delay(10))),
share()
);
output$$.subscribe(console.log);
This works fine when logging into console.
But when I try to use it in React like below utilizing useEffect and useState hooks to update some text:
function App() {
const input$ = new Subject<string>();
const input$$ = input$.pipe(share());
const output$$ = input$$.pipe(
mergeMap(str => of(str).pipe(delay(10))),
share()
);
output$$.subscribe(console.log);
// This works
const [input, setInput] = useState("");
const [output, setOutput] = useState("");
useEffect(() => {
const subscription = input$$.subscribe(setInput);
return () => {
subscription.unsubscribe();
};
}, [input$$]);
useEffect(() => {
const subscription = output$$.subscribe(setOutput);
// This doesn't
return () => {
subscription.unsubscribe();
};
}, [output$$]);
return (
<div className="App">
<input
onChange={event => input$.next(event.target.value)}
value={input}
/>
<p>{output}</p>
</div>
);
}
it starts acting weird/unpredictable (e.g.: sometimes the text is updated in the middle of typing, sometimes it doesn't update at all).
Things I have noticed:
If the inner observable completes immediately/is a promise that
resolves immediately, it works fine.
If we print to console instead of useEffect, it works fine.
I believe this has to do something with the inner workings of useEffect and how it captures and notices outside changes, but cannot get it working.
Any help is much appreciated.
Minimal reproduction of the case:
https://codesandbox.io/s/hooks-and-observables-1-7ygd8
I'm not quite sure what you're trying to achieve, but I found a number of problems which hopefully the following code fixes:
function App() {
// Create these observables only once.
const [input$] = useState(() => new Subject<string>());
const [input$$] = useState(() => input$.pipe(share()));
const [output$$] = useState(() => input$$.pipe(
mergeMap(str => of(str).pipe(delay(10))),
share()
));
const [input, setInput] = useState("");
const [output, setOutput] = useState("");
// Create the subscription to input$$ on component mount, not on every render.
useEffect(() => {
const subscription = input$$.subscribe(setInput);
return () => {
subscription.unsubscribe();
};
}, []);
// Create the subscription to output$$ on component mount, not on every render.
useEffect(() => {
const subscription = output$$.subscribe(setOutput);
return () => {
subscription.unsubscribe();
};
}, []);
return (
<div className="App">
<input
onChange={event => input$.next(event.target.value)}
value={input}
/>
<p>{output}</p>
</div>
);
}
I had a similar task but the goal was to pipe and debounce the input test and execute ajax call.
The simple answer that you should init RxJS subject with arrow function in the react hook 'useState' in order to init subject once per init.
Then you should useEffect with empty array [] in order to create a pipe once on component init.
import React, { useEffect, useState } from "react";
import { ajax } from "rxjs/ajax";
import { debounceTime, delay, takeUntil } from "rxjs/operators";
import { Subject } from "rxjs/internal/Subject";
const App = () => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const [filterChangedSubject] = useState(() => {
// Arrow function is used to init Singleton Subject. (in a scope of a current component)
return new Subject<string>();
});
useEffect(() => {
// Effect that will be initialized once on a react component init.
// Define your pipe here.
const subscription = filterChangedSubject
.pipe(debounceTime(200))
.subscribe((filter) => {
if (!filter) {
setLoading(false);
setItems([]);
return;
}
ajax(`https://swapi.dev/api/people?search=${filter}`)
.pipe(
// current running ajax is canceled on filter change.
takeUntil(filterChangedSubject)
)
.subscribe(
(results) => {
// Set items will cause render:
setItems(results.response.results);
},
() => {
setLoading(false);
},
() => {
setLoading(false);
}
);
});
return () => {
// On Component destroy. notify takeUntil to unsubscribe from current running ajax request
filterChangedSubject.next("");
// unsubscribe filter change listener
subscription.unsubscribe();
};
}, []);
const onFilterChange = (e) => {
// Notify subject about the filter change
filterChangedSubject.next(e.target.value);
};
return (
<div>
Cards
{loading && <div>Loading...</div>}
<input onChange={onFilterChange}></input>
{items && items.map((item, index) => <div key={index}>{item.name}</div>)}
</div>
);
};
export default App;

Categories