CB721
CB721

Reputation: 296

Save axios response to state react hooks

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

Answers (2)

sumit
sumit

Reputation: 15464

There are couple of things you need to refactor

  1. your React Hook useEffect has dependency orders which will re render unlimited times
  2. .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

James
James

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

Related Questions