With React 18 Strict mode, useEffect runs twice, so data fetching in useEffect without workarounds is not good. I watched some videos, read some articles saying that we shouldn't fetch data in this hook, however I have not seen practical examples about how to correctly do it. This is how I do on react 17:
- I have a Zustand store, and it contains the action that will fetch data and populate my state in the store
{
itens: [],
loading: false,
error: null,
async fetchItens(page: number) {
try {
set({
loading: true,
error: null
});
const { data } = await axios.get(`my-url`);
set({
loading: false,
itens: data,
})
} catch(err) {
set({
error: "There was an error.",
loading: false,
})
}
}
}
And in my component I call it like this:
function MyComponent() {
const itens = useStore(state => state.itens);
const loading = useStore(state => state.loading);
const error = useStore(state => state.error);
const fetchItens = useStore(state => state.fetchItens);
useEffect(() => {
fetchItens();
}, []);
if(loading) {
return <div>Loading...</div>;
}
if(error) {
return <div>{error}</div>
}
return (
<div>
{itens.map(item => <span>{item}</span>)}
</div>
);
}
How would I do something like this in React 18?