I'm trying to get the data from Node.js, but it is making like 5000 requests and the server is getting very slow and don't even load some of the other images in other pages. Do I need to limit the requests?
Any solutions?
const [data, SetData] = useState([]);
useEffect(() => {
axios.get(`/api/data/${id}`).then((response) => {
SetData(response.data)
})
})
When I'm adding }, [])
to useEffect the images from Public folder are not showing.
CodePudding user response:
Your effect probably missing the id
as dependency.
Change it be like that:
const [data, setData] = useState([]);
useEffect(() => {
if (id) {
axios.get(`/api/data/${id}`).then((response) => {
setData(response.data)
});
}
}, [id]);
CodePudding user response:
useEffect
runs after every render without the dependencies array, causing infinite loop
useEffect(() => {
axios.get(`/api/data/${id}`).then((response) => {
SetData(response.data)
});
//Infinite loop
});
Provide an empty dependencies array, this will cause the effect function to only run once after the component has rendered the first time.
useEffect(() => {
axios.get(`/api/data/${id}`).then((response) => {
SetData(response.data)
});
// Correct! Runs once after render with empty array
}, []);