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!
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));
}, [])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With