React Hooks, state not updating from fetch within useEffect - javascript

For my react-app/Express app I am trying to update the component state using the useEffects to run once when the component renders. Within useEffect I make a fetch to the express server.
const Favorites = ({ user }) => {
const loggedIn = user.loginname === "" ? false : true;
const [favs, setFavs] = useState([]);
useEffect(() => {
if (loggedIn) {
fetch(`/user/favs/${user.loginname}`)
.then((resp) => resp.json())
.then((data) => {
console.log(data);
setFavs([...data]);
console.log(favs);
});
}
}, []);
return (
<div className="mt-d d-flex justify-content-center">
{loggedIn ? (
<FavoritesList favs={favs} />
) : (
<h3 className="my-2">Please login to use this feature</h3>
)}
</div>
);
};
I make a fetch call on line 11 and am able to print the results on line 14. I then try to update the
component state using setFavs. My issue is that the state seems to not be updated or maybe
there is some async issue.
const FavoritesList = ({ favs, prop }) => {
const [data, setData] = useState([]);
useEffect(() => {
console.log(favs);
// favs.forEach(item => console.log(item))
}, []);
return <h5>Dummy component</h5>;
};
When I try to print favs on line 16 or print favs within the child(FavoritesList) component it is being passed down to, I get an empty array.

When I try to print favs on line 16 or print favs within the child(FavoritesList) component it is being passed down to, I get an empty array.
You're right, it is an async issue: your call to setFavs is async and favs is not yet set on line 16. Calling setFavs will cause your UI to re-render, eventually.
You won't see it in your other useEffect on line 35, either, because that useEffect hook also only runs on first render ([]), so that value is not there yet on first render. To see all updates to favs, try adding it to the dependencies array (like [favs]) or remove the dependencies array altogether.

Change your useEffect on the FavoritesList to:
useEffect(() => {
console.log(favs)
}, [favs])
That way the useEffect will watch for any changes in the favs props. Using an empty array means that the useEffect will only trigger in the first render of the functional component. Meaning that it will not be triggered in any of the props change.

I think above two answers made everyhing clean, here is your lifecycle;
1 -> Favorites component initialized and rendered (state favs = [empty])
2 -> FavoritesList component initialized and rendered (prop favs = [empty])
3 -> FavoritesList useEffect called (console.log(favs) => [empty array])
4 -> Favorites useEffect called (state favs = [now has data])
5 -> FavoritesList component props is updated (prop favs = [has data]
(prop is updated but you didnt call console.log again, after update)
As you can see FavoritesList useEffect called before Favorites useEffect so it called when favs has no data.
So if you add favs prop to array in useEffect in FavoritesList component, you will have one more step;
6 -> FavoritesList useEffect called again (console.log(favs) => [has data])
Because useEffect looks for that arrays elements and if one the elements changed it will triger itself again.
Here is your code with working example: codesandbox.io

Related

Speech recognition problem in react state

I have a problem with a library react-speech-recognition .
newcontent is a state when modify this state inside useeffect
print undefined
and I also want modify this state for transcript
also print undefined
const Room = () => {
let{
transcript,
} = useSpeechRecognition();
const [newContent,setnewcontent]=useState('')
}
console.log(transcript)-->//here successful
useEffect(() => {
console.log(transcript)-->//here undefined
setnewcontent(transcript)
console.log(setnewcontent)-->//here undefined
},[])
Use 2 separate useEffect. One to update the state and other to keep track on it and do the console.log as follows.
// This useEffect will trigger if any change detected in transcript variable
useEffect(() => {
setnewcontent(transcript)
},[transcript])
// This useEffect will trigger if any change detected in newContent state
useEffect(() => {
console.log(newContent)
},[newContent])

In React how can I append values to functional state when it is a dependency of useEffect without triggering another API call?

I have a todo list app which users can read and save items to. Here, Todo is a functional component that queries an API for the users current items on their list using the useEffect() hook. When a successful response is received the data is added to the component's state using useState() and rendered as part of the ItemList component.
When a user submits the form within the AddItemForm component a call back is fired that updates the state of newItem, a dependency of useEffect, which triggers another call to the API and a re-render of the component.
Logically, everything above works. However, it seems wrong to make an extra request to the API simply to receive the data that is already available but I can't find the correct pattern that would allow me to push the item available in useCallback to the items array without causing useEffect to loop infinitely yet still update the ItemList component.
Is there away for my app to push new date from the form submission to items array whilst updating the view and only calling the API once when the page loads?
function Todo() {
const [items, setItems] = useState();
const [newItem, setNewItem] = useState();
useEffect(() => {
fetch('https://example.com/items').then(
(response) => {
setItems(response.data.items);
}, (error) => {
console.log(error);
},
);
}, [newItem]);
const updateItemList = useCallback((item) => {
setNewItem(item);
});
return (
<>
<AddItemForm callback={updateItemList} />
<ItemList items={items} />
</>
);
}
function ItemList(props) {
const { items } = props;
return (
<div>
{ items
&& items.map((item) => <p>{item.description}</p>)}
</div>
);
}
Call API only on start by removing newItem from useEffect(...,[]).
Then add item to the items by destructuring in setItems:
const updateItemList = (item) => {
setItems([...items, item]);
}

React when pass data to child throw props data duplicate

I'm create Activities function component and call child function component called Categories when i send categories list to Categories function component and log "props" data send twice first one is empty and second has data as follow
Activies
function Activities() {
const [category, setCategory] = useState([]);
function handelChange({ target }) {
setCategory({
...category,
[target.name]: target.value,
});
}
useEffect(() => {
getCategories().then((_categories) => setCategory(_categories));
}, []);
return (<Categories category={category} onChange={handelChange} />)
}
and categories component
function Categories(props) {
console.log(props);
return (<div></div>)
}
i'm trying to log props in useEffect but problem still exist
This is happening because of how the life cycle in React works. This is correct and expected behavior. Before you load the categories, it is a blank array on the initial render. Then it gets the categories, updates the state, and re-renders, this time with categories.
renders with the initial state(empty)
goes and fetches categories
re-renders with the categories
This is entirely expected. That double log is the initial render and then the updated state render. Remember React is a heavily async library. The useEffect doesn't happen during render, it happens after render. Every state update will also cause an update and thus another log. It might be helpful to research what will cause a React render and how the life cycle behaves.
I think you handleChange function should update item in a array of object not change the state object completely
function handelChange({ target: {name, value} }) {
setCategory(categories => {
const categoryIndex = categories.findIndex(pr => pr.id === id);
const category = categories[categoryIndex];
return [
...categories.slice(0, categoryIndex)),
{
...category,
[name]: value,
},
...categories.slice(categoryIndex + 1))
]);
}

React Hook who refer to DOM element return "null" on first call

I have got an hook who catch getBoundingClientRect object of a ref DOM element. The problem is, at the first render, it return null and I need to get the value only on first render on my component.
I use it like that in a functional component:
const App = () => {
// create ref
const rootRef = useRef(null);
// get Client Rect of rootRef
const refRect = useBoundingClientRect(rootRef);
useEffect(()=> {
// return "null" the first time
// return "DOMRect" when refRect is update
console.log(refRect)
}, [refRect])
return <div ref={rootRef} >App</div>
}
Here the useBoundingClientRect hook, I call in App Component.
export function useBoundingClientRect(pRef) {
const getBoundingClientRect = useCallback(() => {
return pRef && pRef.current && pRef.current.getBoundingClientRect();
}, [pRef]);
const [rect, setRect] = useState(null);
useEffect(() => {
setRect(getBoundingClientRect());
},[]);
return rect;
}
The problem is I would like to cache boundingClientRect object on init and not the second time component is rerender :
// App Component
useEffect(()=> {
// I would like to get boundingClientRect the 1st time useEffect is call.
console.log(refRect)
// empty array allow to not re-execute the code in this useEffect
}, [])
I've check few tutorials and documentations and finds some people use useRef instead of useState hook to keep value. So I tried to use it in my useboundingClientRect hook to catch and return the boundingClientRect value on the first render of my App component. And it works... partially:
export function useBoundingClientRect(pRef) {
const getBoundingClientRect = useCallback(() => {
return pRef && pRef.current && pRef.current.getBoundingClientRect();
}, [pRef]);
const [rect, setRect] = useState(null);
// create a new ref
const rectRef = useRef(null)
useEffect(() => {
setRect(getBoundingClientRect());
// set value in ref
const rectRef = getBoundingClientRect()
},[]);
// return rectRef for the first time
return rect === null ? rectRef : rect;
}
Now the console.log(rectRef) in App Component allow to access the value on first render:
// App Component
useEffect(()=> {
console.log(refRect.current)
}, [])
But If I try to return refRect.current from useBoundingClientRect hook return null. (What?!)
if anyone can explain theses mistakes to me. Thanks in advance!
You need to understand references, mututation, and the asynchronous nature of updates here.
Firstly, when you use state to store the clientRect properties when your custom hook in useEffect runs, it sets value in state which will reflect in the next render cycle since state updates are asynchronous. This is why on first render you see undefined.
Secondly, when you are returning rectRef, you are essentially returning an object in which you later mutate when the useEffect in useBoundingClientRect runs. The data is returned before the useEffect is ran as it runs after the render cycle. Now when useEffect within the component runs, which is after the useEffect within the custom hook runs, the data is already there and has been updated at its reference by the previous useEffect and hence you see the correct data.
Lastly, if you return rectRef.current which is now a immutable value, the custom hook updates the value but at a new reference since the previous one was null and hence you don't see the change in your components useEffect method.

Why is the cleanup function from `useEffect` called on every render?

I've been learning React and I read that the function returned from useEffect is meant to do cleanup and React performs the cleanup when the component unmounts.
So I experimented with it a bit but found in the following example that the function was called every time the component re-renders as opposed to only the time it got unmounted from the DOM, i.e. it console.log("unmount"); every time the component re-renders.
Why is that?
function Something({ setShow }) {
const [array, setArray] = useState([]);
const myRef = useRef(null);
useEffect(() => {
const id = setInterval(() => {
setArray(array.concat("hello"));
}, 3000);
myRef.current = id;
return () => {
console.log("unmount");
clearInterval(myRef.current);
};
}, [array]);
const unmount = () => {
setShow(false);
};
return (
<div>
{array.map((item, index) => {
return (
<p key={index}>
{Array(index + 1)
.fill(item)
.join("")}
</p>
);
})}
<button onClick={() => unmount()}>close</button>
</div>
);
}
function App() {
const [show, setShow] = useState(true);
return show ? <Something setShow={setShow} /> : null;
}
Live example: https://codesandbox.io/s/vigilant-leavitt-z1jd2
React performs the cleanup when the component unmounts.
I'm not sure where you read this but this statement is incorrect. React performs the cleanup when the dependencies to that hook changes and the effect hook needs to run again with new values. This behaviour is intentional to maintain the reactivity of the view to changing data. Going off the official example, let's say an app subscribes to status updates from a friends' profile. Being the great friend you are, you are decide to unfriend them and befriend someone else. Now the app needs to unsubscribe from the previous friend's status updates and listen to updates from your new friend. This is natural and easy to achieve with the way useEffect works.
useEffect(() => {
chatAPI.subscribe(props.friend.id);
return () => chatAPI.unsubscribe(props.friend.id);
}, [ props.friend.id ])
By including the friend id in the dependency list, we can indicate that the hook needs to run only when the friend id changes.
In your example you have specified the array in the dependency list and you are changing the array at a set interval. Every time you change the array, the hook reruns.
You can achieve the correct functionality simply by removing the array from the dependency list and using the callback version of the setState hook. The callback version always operates on the previous version of the state, so there is no need to refresh the hook every time the array changes.
useEffect(() => {
const id = setInterval(() => setArray(array => [ ...array, "hello" ]), 3000);
return () => {
console.log("unmount");
clearInterval(id);
};
}, []);
Some additional feedback would be to use the id directly in clearInterval as the value is closed upon (captured) when you create the cleanup function. There is no need to save it to a ref.
The React docs have an explanation section exactly on this.
In short, the reason is because such design protects against stale data and update bugs.
The useEffect hook in React is designed to handle both the initial render and any subsequent renders (here's more about it).
Effects are controlled via their dependencies, not by the lifecycle of the component that uses them.
Anytime dependencies of an effect change, useEffect will cleanup the previous effect and run the new effect.
Such design is more predictable - each render has its own independent (pure) behavioral effect. This makes sure that the UI always shows the correct data (since the UI in React's mental model is a screenshot of the state for a particular render).
The way we control effects is through their dependencies.
To prevent cleanup from running on every render, we just have to not change the dependencies of the effect.
In your case concretely, the cleanup is happening because array is changing, i.e. Object.is(oldArray, newArray) === false
useEffect(() => {
// ...
}, [array]);
// ^^^^^ you're changing the dependency of the effect
You're causing this change with the following line:
useEffect(() => {
const id = setInterval(() => {
setArray(array.concat("hello")); // <-- changing the array changes the effect dep
}, 3000);
myRef.current = id;
return () => {
clearInterval(myRef.current);
};
}, [array]); // <-- the array is the effect dep
As others have said, the useEffect was depending on the changes of "array" that was specified in the 2nd parameter in the useEffect. So by setting it to empty array, that'd help to trigger useEffect once when the component mounted.
The trick here is to change the previous state of the Array.
setArray((arr) => arr.concat("hello"));
See below:
useEffect(() => {
const id = setInterval(() => {
setArray((arr) => arr.concat("hello"));
}, 3000);
myRef.current = id;
return () => {
console.log("unmount");
clearInterval(myRef.current);
};
}, []);
I forked your CodeSandbox for demonstration:
https://codesandbox.io/s/heuristic-maxwell-gcuf7?file=/src/index.js
Looking at the code I could guess its because of the second param [array]. You are updating it, so it will call a re-render. Try setting an empty array.
Every state update will call a re-render and unmount, and that array is changing.
It seems expected. As per the documentation here, useEffect is called after first render, every update and unmount.
https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
Tip
If you’re familiar with React class lifecycle methods, you can think
of useEffect Hook as componentDidMount, componentDidUpdate and before
componentWillUnmount combined.
This is a Jest test that shows the render and effect order.
As you can see from the expect, once the dependency foo changes due to the state update it triggers a NEW render followed by the cleanup function of the first render.
it("with useEffect async set state and timeout and cleanup", async () => {
jest.useFakeTimers();
let theRenderCount = 0;
const trackFn = jest.fn((label: string) => { });
function MyComponent() {
const renderCount = theRenderCount;
const [foo, setFoo] = useState("foo");
useEffect(() => {
trackFn(`useEffect ${renderCount}`);
(async () => {
await new Promise<string>((resolve) =>
setTimeout(() => resolve("bar"), 5000)
);
setFoo("bar");
})();
return () => trackFn(`useEffect cleanup ${renderCount}`);
}, [foo]);
++theRenderCount;
trackFn(`render ${renderCount}`);
return <span data-testid="asdf">{foo}</span>;
}
const { unmount } = render(<MyComponent></MyComponent>);
expect(screen.getByTestId("asdf").textContent).toBe("foo");
jest.advanceTimersByTime(4999);
expect(screen.getByTestId("asdf").textContent).toBe("foo");
jest.advanceTimersByTime(1);
await waitFor(() =>
expect(screen.getByTestId("asdf").textContent).toBe("bar")
);
trackFn("before unmount");
unmount();
expect(trackFn.mock.calls).toEqual([
['render 0'],
['useEffect 0'],
['render 1'],
['useEffect cleanup 0'],
['useEffect 1'],
['before unmount'],
['useEffect cleanup 1']
])
});

Categories