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 ponentDidMount() in functional ponents. What alternative can I use?
Edit: When I remove the useEffect(), the errors keep ing 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!
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 ponentDidMount() in functional ponents. What alternative can I use?
Edit: When I remove the useEffect(), the errors keep ing 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!
Share Improve this question edited Dec 2, 2020 at 18:40 Ziv Aviv asked Dec 2, 2020 at 18:31 Ziv AvivZiv Aviv 711 silver badge7 bronze badges 3- You make the request after every render – zb22 Commented Dec 2, 2020 at 18:36
- @zb22 But even if I remove the useEffect() it still stays the same – Ziv Aviv Commented Dec 2, 2020 at 18:37
- see my updated answer – zb22 Commented Dec 2, 2020 at 18:43
1 Answer
Reset to default 6You 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));
}, [])