Async/Await in useEffect(): how to get useState() value? - javascript

I have the following code snippet. Why is my limit always 0 in my fetchData? If I were to console.log(limit) outside of this function it has the correct number. Also If I dont use useState but a variable instead let limit = 0; then it works as expected
I also added limit as a dependency in useEffect but it just keeps triggering the function
const [currentData, setData] = useState([]);
const [limit, setLimit] = useState(0);
const fetchData = async () => {
console.log(limit);
const { data } = await axios.post(endpoint, {
limit: limit,
});
setData((state) => [...state, ...data]);
setLimit((limit) => limit + 50);
};
useEffect(() => {
fetchData();
window.addEventListener(`scroll`, (e) => {
if (bottomOfPage) {
fetchData();
}
});
}, []);

When you pass an empty dependency array [] to useEffect, the effect runs only once on the initial render:
If you pass an empty array ([]), the props and state inside the effect
will always have their initial values.
If you want to run an effect and clean it up only once (on mount and
unmount), you can pass an empty array ([]) as a second argument. This
tells React that your effect doesn’t depend on any values from props
or state, so it never needs to re-run. This isn’t handled as a special
case — it follows directly from how the dependencies array always
works.
useEffect docs
The initial state of limit is 0 as defined in your useState call. Adding limit as a dependency will cause the effect to run every time limit changes.

One way to get around your issue is to wrap the fetchData method in a useCallback while passing the limit variable to the dependency array.
You can then pass the function to the dependency array of useEffect and also return a function from inside of useEffect that removes event listeners with outdated references.
You should also add a loading variable so that the fetchData function doesn't get called multiple times while the user is scrolling to the bottom:
const [currentData, setData] = useState([]);
const [limit, setLimit] = useState(0);
const [loading, setLoading] = useState(false);
const fetchData = useCallback(async () => {
console.log(limit);
// Prevent multiple endpoint calls when scrolling near the end with a loading state
if (loading) {
return;
}
setLoading(true);
const { data } = await axios.post(endpoint, { limit });
setData((state) => [...state, ...data]);
setLimit((limit) => limit + 50);
setLoading(false);
}, [limit, loading]);
// Make the initial request on the first render only
useEffect(() => {
fetchData();
}, []);
// Whenever the fetchData function changes update the event listener
useEffect(() => {
const onScroll = (e) => {
if (bottomOfPage) {
fetchData();
}
};
window.addEventListener(`scroll`, onScroll);
// On unmount ask it to remove the listener
return () => window.removeEventListener("scroll", onScroll);
}, [fetchData]);

Related

Maximum depth exceeded while using useEffect

I am trying to implement a simple search algorithm for my products CRUD.
The way I thought to do it was entering the input in a search bar, and the products that matched the search would appear instantly every time the user changes the input, without needing to hit a search button.
However, the way I tried to do it was like this:
function filterProducts (productName, productList) {
const queryProducts = productList.filter((prod)=> {
return prod.title === productName;
});
return queryProducts;
}
function HomePage () {
const [productList, setProductList] = useState([]);
const [popupTrigger, setPopupTrigger] = useState('');
const [productDeleteId, setProductDeleteId] = useState('');
const [queryString, setQueryString] = useState('');
let history = useHistory();
useEffect(() => {
if (queryString.trim() === "") {
Axios.get("http://localhost:3001/api/product/get-all").then((data) => {
setProductList(data.data);
});
return;
}
const queryProducts = filterProducts(queryString, productList);
setProductList(queryProducts);
}, [queryString, productList]);
I know that productList changes every render, and that's probably why it isn't working. But I didn't figure out how can I solve the problem. I've seen other problems here and solutions with useReducer, but I none of them seemed to help me.
The error is this one below:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
what you are doing here is fetching a product list and filtering it based on the query string and using that filtered list to render the UI. So ideally your filteredList is just a derived state based on your queryString and productList. So you can remove the filterProducts from your useEffect and move it outside. So that it runs when ever there is a change in the state.
function filterProducts (productName = '', productList = []) {
return productName.trim().length > 0 ? productList.filter((prod)=> {
return prod.title === productName;
}); : productList
}
function HomePage () {
const [productList, setProductList] = useState([]);
const [queryString, setQueryString] = useState('');
useEffect(() => {
if (queryString.trim() === "") {
Axios.get("http://localhost:3001/api/product/get-all").then((data) => {
setProductList(data.data);
});
}
}, [queryString]);
// query products is the derived state
const queryProducts = filterProducts(queryString, productList);
// Now instead of using productList to render something use the queryProducts
return (
{queryProducts.map(() => {
.....
})}
)
If you want the filterProducts to run only on change in queryString or productList then you can wrap it in useMemo
const queryProducts = React.useMemo(() => filterProducts(queryString, productList), [queryString, productList]);
When you use a setState function in a useEffect hook while having the state for that setState function as one of the useEffect hook's dependencies, you'll get this recursive effect where you end up infinitely re-rendering your component.
So, first of all we have to remove productList from the useEffect. Then, we can use a function to update your state instead of a stale update (like what you're doing in your example).
function filterProducts (productName, productList) {
const queryProducts = productList.filter((prod)=> {
return prod.title === productName;
});
return queryProducts;
}
function HomePage () {
const [productList, setProductList] = useState([]);
const [popupTrigger, setPopupTrigger] = useState('');
const [productDeleteId, setProductDeleteId] = useState('');
const [queryString, setQueryString] = useState('');
let history = useHistory();
useEffect(() => {
if (queryString.trim() === "") {
Axios.get("http://localhost:3001/api/product/get-all").then((data) => {
setProductList(data.data);
});
return;
}
setProductList(prevProductList => {
return filterProducts(queryString, prevProductList)
});
}, [queryString]);
Now, you still get access to productList for your filter, but you won't have to include it in your dependencies, which should take care of the infinite re-rendering.
I recommend several code changes.
I would separate the state that immediately reflects the user input at all times from the state that represents the query that is send to the backend. And I would add a debounce between the two states. Something like this:
const [query, setQuery] = useState('');
const [userInput, setUserInput] = useState('');
useDebounce(userInput, setQuery, 750);
I would split up the raw data that was returned from the backend and the filtered data which is just derived from it
const [products, setProducts] = useState([]);
const [filteredProducts, setFilteredProducts] = useState([]);
I would split up the useEffect and not mix different concerns all into one (there is no rule that you cannot have multiple useEffect)
useEffect(() => {
if (query.trim() === '') {
Axios
.get("http://localhost:3001/api/product/get-all")
.then((data) => { setProducts(data.data) });
}
}, [query]);
useEffect(
() => setFilteredProducts(filterProducts(userInput, products)),
[userInput, products]
);

React app keeps re-rendering with custom useRequest hook

In my application I created a custom hook to make API requests:
const useRequest = (promise) => {
const [data, setData] = useState({});
const [loading, setLoading] = useState(false);
const [error, setError] = useState({});
useEffect(() => {
let ignore = false;
const fetchProduct = async () => {
try {
setLoading(true);
const response = await promise;
if (!ignore) setData(response);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchProduct();
return () => {
ignore = true;
};
}, [promise]);
return { data, loading, error };
};
export default useRequest;
And in my component I use it as:
const { data, loading, error } = useRequest(api.user.getAll());
where api.user.getAll() is a function that returns a promise. The component renders and it displays the data however it keeps re-rendering and refetching data multiple times. What might be the problem that is causing this? Are there multiple instances of promises being created that trigger the hook to run again?
where api.user.getAll() is a function that returns a promise. [...] Are there multiple instances of promises being created that trigger the hook to run again?
Yes, every time your component gets rendered, it calls api.user.getAll(). Since new Promise (or an async function) will always return a fresh Promise object (and hook deps use strict equality for comparison), the effect is re-run.
My go-to hammer for requests like this these days is swr; maybe look into it?

How to use setTimeout() along with React Hooks useEffect and setState?

I want to wait for 10 seconds for my API call to fetch the category list array from backend and store in hook state. If nothing is fetched in 10 sec, I want to set error hook state to true.
But the problem is even after the array is fetched initially, the error state is set to true and categoriesList array in state blanks out after 10 sec.
import React, { useState, useEffect } from "react";
import { doGetAllCategories } from "../helper/adminapicall.js";
const ViewCategories = () => {
let [values, setValues] = useState({
categoriesList: "",
error: false,
});
let { categoriesList, error } = values;
const preloadCategories = () => {
doGetAllCategories()
.then((data) => {
if (data.error) {
return console.log("from preload call data - ", data.error);
}
setValues({ ...values, categoriesList: data.categories });
})
.catch((err) => {
console.log("from preload - ", err);
});
};
useEffect(() => {
preloadCategories();
let timerFunc = setTimeout(() => {
if (!categoriesList && !error) {
setValues({
...values,
error: "Error fetching category list... try after some time !",
});
}
}, 10000);
return () => {
clearTimeout(timerFunc);
};
}, []);
//...further code
The problem is that the useEffect callback is a closure over categoriesList, so you'll always see the initial categories list inside the callback, and you won't see any changes to it. Now one could add categoriesList as a dependency to the useEffect hook, that way the hook will be recreated on every categoriesList change, and thus you can see the changed version:
useEffect(/*...*/, [categoriesList]);
Now the good thing is, that by updating the hook the timeout also gets canceled, so if the category list is set, we just don't have to create a new timeout:
useEffect(() => {
if(!categoriesList && !error) {
let timerFunc = setTimeout(() => {
setValues({
...values,
error: "Error fetching category list... try after some time !",
});
}, 10000);
return () => clearTimeout(timerFunc);
}
}, [!categoriesList, !error]); // some minor optimization, changes to the list don't bother this hook
I recommend you to read this blog post on useEffect by Dan Abramov.
The problem with your code is that you expect to have a change of the state of the component inside the useEffect hook. Instead, you create two variables inside the useEffect that track whether the limit of 10 sec has passed or the data is fetched. In contrary to state variables, you can expect these variables to change because they lie within the same useEffect.
export default function App() {
const [data, setData] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
let didCancel = false;
let finished = false;
async function fetchData() {
const data = await subscribeAPI();
if (!didCancel) {
finished = true;
setData(data);
}
}
const id = setTimeout(() => {
didCancel = true;
if (!finished) {
setError("Errorrrr");
}
}, 10000);
fetchData();
return () => {
clearTimeout(id);
};
}, []);

React hooks error: Rendered more hooks than during the previous render

I used to have a function component act as a page:
export default function NormalList(props) {
const pageSize = 20;
const [page, setPage] = useState(1)
const [searchString, setSearchString] = useState(null);
const [creditNotes, setCreditNotes] = useState(() => getCreditNoteList());
const [ordering, setOrdering] = useState(null);
useEffect(() => getCreditNoteList(), [page, searchString, ordering]);
function getCreditNoteList() {
API.fetchCreditNoteList({
account_id: props.customerId, page, page_size: pageSize, searchString, ordering
}).then(data => {
setCreditNotes(data);
});
}
return (<>{creditNotes.results.map(record => <...>}</>)
}
And this has been running fine, but recently I need to wrap around NormalList with ListPage component:
export default function ListPage(props) {
const customerId = props.match.params.customer_id;
return (<div>...<div><NormalList/></div></div>)
}
Then all the sudden I am getting this error Rendered more hooks than during the previous render.
It seems to me that setCreditNotes(data) inside getCreditNoteList is causing the error, but I don't know why.
So there are a couple of things you need to fix. First of all you should remove your function call from the useState function, you should only perform your side effects inside a useEffect hook see React Docs.
The next thing is whenever you decide to use the dependency array to your useEffect hook you should include all the dependencies of useEffect i.e all the props, state including functions inside your function component that you used inside your useEffect hook. So the Rule of Thumb is Never Lie About Your Dependencies! otherwise you will shoot yourself in the foot.
So the easiest option is to move your getCreditNoteList function inside your useEffect hook and add all the dependencies of your useEffect hook to the dependency array.
export default function NormalList({ customerId }) {
const pageSize = 20;
const [page, setPage] = useState(1)
const [searchString, setSearchString] = useState(null);
const [creditNotes, setCreditNotes] = useState({});
const [ordering, setOrdering] = useState(null);
useEffect(() => {
function getCreditNoteList() {
API.fetchCreditNoteList({
account_id: customerId,
page,
page_size: pageSize,
searchString,
ordering
}).then(data => {
setCreditNotes(data);
});
}
getCreditNoteList(),
// add ALL! dependencies
}, [page, searchString, ordering, pageSize, customerId]))
return (
<> </>
)
}
Second Option
If you want to use the getCreditNoteList function elsewhere and want to keep it outside your useEffect hook you can do that by wrapping your getCreditNoteList logic inside the useCallback hook as shown below and add the function to your dependency array inside your useEffect hook for reasons i mentioned earlier.
export default function NormalList({ customerId }) {
const pageSize = 20;
const [page, setPage] = useState(1)
const [searchString, setSearchString] = useState(null);
const [creditNotes, setCreditNotes] = useState({});
const [ordering, setOrdering] = useState(null);
const getCreditNoteList = useCallback(() => {
API.fetchCreditNoteList({
account_id: customerId,
page,
page_size: pageSize,
searchString,
ordering
}).then(data => {
setCreditNotes(data);
});
// the function only changes when any of these dependencies change
},[page, searchString, ordering, pageSize, customerId])
useEffect(() => {
getCreditNoteList(),
},[getCreditNoteList])
return (
<> </>
)
}
OK My problem was that I had 2 issues with importing the elements, first being pycharm cleverly automatically imported them wrong, and secondly being I didn't import one of the component at all.
I wish the error message could be a bit more specific than "Rendered more hooks than during the previous render".
Also I tested I didn't need to move function body getCreditNoteList inside useEffect.
Thanks to #chitova263 for spending the time to help out.

useEffect spamming requests

State
const [user, setUser] = useState({});
checkIfUserIsEnabled()
async function checkIfUserIsEnabled() {
const res = await fetch("http://localhost:8080/users/finduserbytoken?id=" +
getTokenIdFromURL);
res.json()
.then(res => setUser(res))
.catch(err => setErrors(err));
}
useEffect When i call my checkIfUserIsEnabled() in the useEffect below it gets rendered once and displays the false version in the return method.
useEffect(() => {
verifyEmail(getTokenIdFromURL);
checkIfUserIsEnabled();
return () => {
/* cleanup */
};
}, [/* input */])`
useEffect (2th) If i do it like this instead, it keeps spamming the requests towards my API and displays true.
useEffect(() => {
checkIfUserIsEnabled();
});
Return
return (
<div className="emailVerificationWrapper">
{user.enabled
? <h1>Thank you for registrating, {user.firstName}. Account is verified!</h1>
: <h1>Attempting to verify account...</h1>}
</div>
)
To my question(s): Why does the second useEffect spam the request? and is there a way i can make the request being rendered every ~2-3 second instead of the spam? and could i make it stop doing the request once it actually returns true?
The effect hook runs when the component mounts but also when the component updates. Because we are setting the state after every data fetch, the component updates and the effect runs again.
It fetches the data again and again. That's a bug and needs to be avoided. We only want to fetch data when the component mounts. That's why you can provide an empty array(or something which doesn't change) as second argument to the effect hook to avoid activating it on component updates(or only when that parameter changes) but only for the mounting of the component.
let URL = `http://localhost:8080/users/finduserbytoken?id=`;
async function checkIfUserIsEnabled() {
const res = await fetch(`$(URL)` +
getTokenIdFromURL);
res.json()
.then(res => {setUser(res); return Promise.resolve()})
.catch(err => {setErrors(err); return Promise.reject()});
}
useEffect(() => {
const abortController = new AbortController();
const fetchData = async() => await checkIfUserIsEnabled();
fetchData();
return () => {
abortController.abort();
};
}, [URL]);
useEffect(() => {
checkIfUserIsEnabled();
}); <-- no dependency
As your useEffect doesn't have any dependency it will run on every render, so every time you change some state and your component re-renders it will send requests.

Categories

Resources