简体   繁体   中英

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.

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(..., [])

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";
            }
    }, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM