Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERR_INSUFFICIENT_RESOURCES errors on Axios GET request In React

I have a mongoDB which contains items in a shop. Using React, I want to render item cards based on each entry in the database. For that matter, I am using Axios for sending a GET request for my server that will handle pulling the data from the database.

My React code is this:

import React, { useEffect, useState } from 'react';
import axios from "axios";

function App() {
const [items, setItems] = useState([{}]);
useEffect(() => {
    axios.get('/item').then(res => {
       (res.data).forEach(entry => {
           setItems(prevItems => {
               return [...prevItems, entry];
           })
       });
    }).catch(err => console.log(err));
})

return (
    ...
)
}

I'm having success getting the data, but in my Chrome console I get non-stop ERR_INSUFFICIENT_RESOURCES errors which eventually leads to Chrome crashes. Why is this error happening? I am using useEffect() since the React docs says it is the equivalent to componentDidMount() in functional components. What alternative can I use?

Edit: When I remove the useEffect(), the errors keep coming and using the React dev tools I see that in items I have 80 entries which means the request is triggered 10+ times and I don't understand how.

Thanks!

like image 838
Ziv Aviv Avatar asked Apr 28 '26 14:04

Ziv Aviv


1 Answers

You make the request after every render. add [] as second argument of useEffect() in order to make the request once after first render.

const [items, setItems] = useState([{}]);
useEffect(() => {
    axios.get('/item').then(res => {
       setItems(res.data)
    }).catch(err => console.log(err));
}, [])
like image 65
zb22 Avatar answered May 01 '26 03:05

zb22