Reputation: 296
I am trying to save the response I get from Axios to state using hooks. However, whenever I attempt to use the hook, the component continues to re-render an unlimited number of times.
const [orders, setOrders] = useState([]);
const getUserOrders = async () => {
await API.getOrders(window.sessionStorage.id)
.then(res => setOrders(res.data.ordersArr))
.catch(err => console.log(err));
}
useEffect(() => {
if (logged_in) {
getUserOrders();
} else {
window.location.href = "/login";
}
}, [orders])
If I console log res.data.ordersArr instead of using the setOrders hook, I am able to see the expected data. When I use the hook, it keeps re-rendering.
Upvotes: 1
Views: 2178
Reputation: 15464
There are couple of things you need to refactor
orders
which will re render unlimited times .then
after await dont make any sense , either get rid of async / await or include the promise callback
const getUserOrders = () => {
API.getOrders(window.sessionStorage.id)
.then(res => setOrders(res.data.ordersArr))
.catch(err => console.log(err));
}
useEffect(() => {
if (logged_in) {
getUserOrders();
} else {
window.location.href = "/login";
}
}, [])
Upvotes: 1
Reputation: 82136
Your useEffect
hook will re-run each time the orders
state changes, when your useEffect
hook runs you fetch data from the API and then set the orders
. This in turn then triggers a render with a new value for orders
thus invalidating the useEffect
call and causing it to fire again which ultimately leads to the infinite loop.
You simply want to force the useEffect
to run once by passing an empty dependency list useEffect(..., [])
Upvotes: 1