How to fix multiple call fetch data in forEach() using React Hooks - reactjs

In react Hooks, I am trying to fetch data from the API array but in the Foreach function, the API call causes infinity.
How to fix this?
const [symbols, setSymbols] = useState([]);
getPortfolioSymbolList(portfolio_name).then(data => data.json()).then(res => {
res.forEach((symbol_data)=>{
fetchPrice(symbol_data.symbol).then(price => {
setSymbols(price);
});
})
}
function fetchPrice(symbol){
const price = fetch(`api_url`)
.then(chart => chart.json())
return price;
}
Here, call fetchPrice() causes in infinite.

Setting the state will always cause a rerender
What happens in your code is the request is made and then the data is set causing a rerender. Then because of the rerender the request is made again and sets the state again and causes the rerender again.
If you have a request for data you probably want to put a React.useEffect so it only requests once.
React.useEffect(() => {
/* your data request and data set */
}, []); // the [] will only fire on mount.

Is is because your setSymbols call inside forEach makes component rerender (reload) - it means that all of your main component function is call again and again... getPortfolioSymbolList too. You have to use useEffect hook to resolve this problem. Your getPortfolioSymbolList() API call should be inside useEffect.
https://reactjs.org/docs/hooks-effect.html

PROBLEM
Your first symbol is updated in your API call, which triggers a re-render of the component calling the API call to go on an infinite loop.
SOLUTION
Wrap your API in your useEffect. The function inside your useEffect will only be called once. See useEffect docs here
You need to use for await of to loop asynchronously. forEach can't loop asynchronously. See for await of docs here
Update your symbols once all the data is collected.
function Symbols() {
const [symbols, setSymbols] = useState([]);
React.useEffect(() => {
async function fetchSymbols() {
const portfolio = await getPortfolioSymbolList(portfolio_name);
const jsonPortfolios = await data.json();
const symbols = [];
for await (let jsonPortfolio of jsonPortfolios) {
const price = await fetchPrice(jsonPortfolio.symbol);
symbols.push(price);
}
setSymbols(symbols);
}
fetchSymbols();
}, []);
return /** JSX **/
}

Related

My custom React hook method "useFetch" is running 8 times when called

Hope anyone is able to help me with a custom react hook.
My custom react hook "useFetch" is running 8 times when called.
Can anyone see, why it is running 8 times when the custom "useFetch" hook is called?
I am a bit new to React, but it seems like I am using useEffect method wrong. Or maybe I need to use another method.
UseFetch hook method:
import React, { useState, useEffect } from "react";
export const useFetch = function (
options = {
IsPending: true,
},
data = {}
) {
// load data
const [loadData, setLoadData] = useState(null);
// pending
const [isPending, setIsPending] = useState(false);
// error
const [isError, setIsError] = useState(false);
useEffect(() => {
// method
const fetchData = async function () {
// try
try {
// set pending
setIsPending(true);
// response
const response = await fetch(data.url, data);
// handle errors
if (response.status !== 200 && response.status !== 201) {
// throw new error with returned error messages
throw new Error(`Unable to fetch. ${response.statusText}`);
}
// convert to json
const json = await response.json();
// set load data
setLoadData(json);
// set error
setIsError(false);
// set pending
setIsPending(false);
// catch errors
} catch (err) {
// set error
setIsError(`Error fetching data: ${err.message}`);
// set pending
setIsPending(false);
}
};
// invoke fetch data method
fetchData();
}, []);
// return
return {
loadData,
isPending,
isError,
};
};
export default useFetch;
Everytime you change a state in a hook, the component that has the hook in it will rerender, making it call the function again.
So let's start counting the renders/rerenders by the change of state:
Component mounted
setIsPending(true)
setLoadData(json)
setIsPending(false)
(depending if it's successful or not you might get more state changes, and therefore rerenders, and therefore hook being called again)
So 4 is not 8, so why are you getting 8?
I presume you are using React18, and React18 on development and StrictMode will call your useEffect hooks twice on mount: React Hooks: useEffect() is called twice even if an empty array is used as an argument
What can you do to avoid this?
First of all, check on the network tab how many times you are actually fetching the data, I presume is not more than 2.
But even so you probably don't want to fetch the data 2 times, even though this behaviour won't be on production and will only be on development. For this we can use the useEffect cleanup function + a ref.
const hasDataFetched = useRef(false);
useEffect(() => {
// check if data has been fetched
if (!hasDataFetched.current) {
const fetchData = async function () {
// fetch data logic in here
};
fetchData();
}
// cleanup function
return () => {
// set has data fetched to true
hasDataFetched.current = true;
};
}, []);
Or as you suggested, we can also add data to the dependency array. Adding a variable to a dependency array means the useEffect will only be triggered again, when the value of the variable inside the dependency array has changed.
(Noting that data is the argument you pass to the useFetch hook and not the actual data you get from the fetch, maybe think about renaming this property to something more clear).
useEffect(() => {
// check if data has been fetched
const fetchData = async function () {
// fetch data logic in here
};
fetchData();
}, [data]);
This will make it so, that only if loadData has not been fetched, then it will fetch it. This will make it so that you only have 4 rerenders and 1 fetch.
(There is a good guide on useEffect on the React18 Docs: https://beta.reactjs.org/learn/synchronizing-with-effects)
Every time you change the state within the hook, the parent component that calls the hooks will re-render, which will cause the hook to run again. Now, the empty array in your useEffect dependency should be preventing the logic of the hook from getting called again, but the hook itself will run.

Why am I getting an infinite loop in my useEffect (react.js)

Basically I have a function called getWeatherForecast which gets some weather data from an api however, I am getting an infinite loop and it keeps requesting for the data an infinite number of times.
Here is my function
const getWeatherForecast = async () => {
const weatherForecast = await axios.get(`${API_ENDPOINT}lat=${props.latitude}&lon=${props.longitude}&exclude=hourly,daily&appid=${API_KEY}`)
console.log(weatherForecast)
setWeatherDetails(weatherForecast)
}
This is how I used the useEffect
useEffect(() => {
getWeatherForecast()
// console.log(`This is the forecast ${weatherDetails}`)
} , [getWeatherForecast])
Any idea why I am getting an infinite loop ?
Because this:
getWeatherForecast
is a function which gets recreated on each render.
Inside that function you are calling a setWeatherDetails, which triggers a render. Hence on the next render a new instance of that function is created, which is different from the previous one, and useEffect is called again.
Wrap that function in useCallback.
let getWeatherForecast = React.useCallback(async () => {
const weatherForecast = await axios.get(
`${API_ENDPOINT}lat=${props.latitude}&lon=${props.longitude}&exclude=hourly,daily&appid=${API_KEY}`
);
console.log(weatherForecast);
setWeatherDetails(weatherForecast);
}, [
/*
* put the dependencies here
* if API_ENDPOINT and API_KEY are defined outside the component no need to put them as dependency
*/
props.latitude,
props.longitude,
]);
But If I remember correctly linter may complain about dependency like props.latitude and suggest to assign it to some variable before the useCallback, and then use that as a dependency like:
let latitude = props.latitude; // then use latitude as dependency

Why is this reactjs useEffect function running endlessly?

Here is a useEffect hook that I used in reactjs:
Problem: The useEffect calls fetchAllCategories() endlessly. Infact, over 1000 requests until I terminate. I only want it to run on page mount and when I click on the button to change catName state. What could I be doing wrong?
const [catName, setCategories] = useState([]);
const categoryRef = useRef();
useEffect(()=>{
const fetchAllCategories = async () =>{
try{
const res = await axios.get(`${BASE_URL}/category`)
return setCategories(res.data);
}catch(err){
}
}
fetchAllCategories()
}, [catName])
//create new category
const createNewCategory = async ()=>{
const categoryName = {
catName: categoryRef.current.value
}
try{
const response = await axiosPrivate.post(`${BASE_URL}/category`, categoryName, { withCredentials: true,
headers:{authorization: `Bearer ${auth}`}
})
return setCategories([response.data])
}catch(err){
}
}
The button that triggers changes in catName
<button onClick={ createNewCategory} className='button-general'>Create</button>
You trigger the effect to be run on change of catNames, and then change catNames from the effect itself. This results in the endless self-triggering of the effect.
One solution could be to make your effect depend on nothing:
useEffect(() => {
....
}, []);
Thank you all for pointing out the issue to me. Since I now know the issue, I have been able to fix it. All I did was create another state and made the useEffect to depend on it. Then, whenever the button is clicked, I change the state to the opposite of the initial state. This works and doesnt cause endless calls.
If you absolutely need catName as a dependency, this can work for you:
useEffect(() => {
const fetchAllCategories = async () => {
try {
const res = await axios.get(`${BASE_URL}/category`);
return setCategories(res.data);
} catch (err) {}
};
fetchAllCategories();
}, [JSON.stringify(catName)]);
This is happening because you update the catName state inside the useEffect using setCategories(res.data) this keeps triggering your useEffect thus an infinite loop
You programmed it to run endlessly.
REASON
See, this React hook useEffect has two parameters:
Effect, the callback function which is called whenever the component renders.
List of Dependencies on which the useEffect hook depends and re-renders if any such dependency is updated.
Now, in your case, you've passed catName as a dependency, whose state is updated when the button is clicked. This causes useEffect to call the callback function which calls fetchAllCategories() which also update catName. And this causes an endless loop.
SOLUTION
Just remove the dependency from useEffect as:
useEffect(() {
...
}, []);
Now, updating catName won't cause the effect (The Callback function) to be called endlessly.

Infinite re-render in functional react component

I am trying to set the state of a variable "workspace", but when I console log the data I get an infinite loop. I am calling the axios "get" function inside of useEffect(), and console logging outside of this loop, so I don't know what is triggering all the re-renders. I have not found an answer to my specific problem in this question. Here's my code:
function WorkspaceDynamic({ match }) {
const [proposals, setProposals] = useState([{}]);
useEffect(() => {
getItems();
});
const getItems = async () => {
const proposalsList = await axios.get(
"http://localhost:5000/api/proposals"
);
setProposals(proposalsList.data);
};
const [workspace, setWorkspace] = useState({});
function findWorkspace() {
proposals.map((workspace) => {
if (workspace._id === match.params.id) {
setWorkspace(workspace);
}
});
}
Does anyone see what might be causing the re-render? Thanks!
The effect hook runs every render cycle, and one without a dependency array will execute its callback every render cycle. If the effect callback updates state, i.e. proposals, then another render cycle is enqueued, thus creating render looping.
If you want to only run effect once when the component mounts then use an empty dependency array.
useEffect(() => {
getItems();
}, []);
If you want it to only run at certain time, like if the match param updates, then include a dependency in the array.
useEffect(() => {
getItems();
}, [match]);
Your use of useEffect is not correct. If you do not include a dependency array, it gets called every time the component renders. As a result your useEffect is called which causes setProposals then it again causes useEffect to run and so on
try this
useEffect(() => {
getItems();
} , []); // an empty array means it will be called once only
I think it's the following: useEffect should have a second param [] to make sure it's executed only once. that is:
useEffect(() => {
getItems();
}, []);
otherwise setProposal will modify the state which will trigger a re-render, which will call useEffect, which will make the async call, which will setProposal, ...

React: Stop hook from being called every re-rendering?

Somewhat new to React and hooks in React. I have a component that calls a communications hook inside of which a call to an API is made with AXIOS and then the JSON response is fed back to the component. The issue I'm having is the component is calling the hook like six times in a row, four of which of course come back with undefined data and then another two times which returns the expected JSON (the same both of those two times).
I did a quick console.log to double check if it was indeed the component calling the hook mulitple times or it was happening inside the hook, and it is the component.
How do I go about only have the hook called only once on demand and not multiple times like it is? Here's the part in question (not including the rest of the code in the widget because it doesn't pertain):
export default function TestWidget() {
//Fetch data from communicator
console.log("called");
const getJSONData = useCommunicatorAPI('https://jsonplaceholder.typicode.com/todos/1');
//Breakdown passed data
const {lastName, alertList, warningList} = getJSONData;
return (
<h1 id="welcomeTitle">Welcome {lastName}!</h1>
);
}
export const useCommunicatorAPI = (requestAPI, requestData) => {
const [{ data, loading, error }, refetch] = useAxios('https://jsonplaceholder.typicode.com/todos/1', []);
console.log("data in Communicator:", data);
return {data};
}
I would use the useEffect hook to do this on mount and whenever any dependencies of the request change (like if the url changed).
Here is what you will want to look at for useEffect
Here is what it might look like:
const [jsonData, setJsonData] = React.useState({})
const url = ...whatver the url is
React.useEffect(() => {
const doFetch = async () => {
const jsonData = await useAxios(url, []);;
setJsonData(jsonData)
}
doFetch();
}, [url])
...use jsonData from the useState
With the above example, the fetch will happen on mount and if the url changes.
Why not just use the hook directly?
export default function TestWidget() {
const [{ data, loading, error }, refetch] =
useAxios('https://jsonplaceholder.typicode.com/todos/1', []);
return (<h1 id="welcomeTitle">Welcome {lastName}!</h1>);
}
the empty array [] makes the hook fire once when called
Try creating a function with async/await where you fetch the data.
Here can you learn about it:
https://javascript.info/async-await

Resources