Reputation: 1581
I am new to Meteor and trying to fetch data from an API by passing different parameters from an array but it's running into an infinite loop. I can see the object is rendered again and again and the value keeps on changing instead of appending the correct value into the object after the response from the call.
let [projectvalue, setProjectvalue] = useState({});
let projectList = ['abc','def','bbb','sss'];
projectList.map(projectName => {
useEffect(
(project = projectName) =>
Meteor.call(
'method.getValue',
{ project },
(error, resp) => {
if (error) throw new Error(error);
resp.status.map(val => {
if(val.key == "data"){
setProjectvalue({...projectvalue, [projectName] : val.actualValue })
}
})
}
),
);
});
console.log(projectvalue);
I need to get the actualValues from the response for different project names.
Edited:
useEffect(() => {
projectList.map(project => {
Meteor.call(
'method.getValue',
{ project },
(error, resp) => {
if (error) throw new Error(error);
resp.status.map(val => {
if(val.key == "data"){
setProjectvalue({...projectvalue, [projectName] : val.actualValue })
}
})
}
)
})
}
,[projectList]);
Upvotes: 1
Views: 62
Reputation: 27765
You are missing dependency array for useEffect
hook. And hooks should be placed on top level at function scope. Not inside map
method:
useEffect(
projectList.map(projectName => {
Meteor.call(
'method.getValue',
{ projectName },
(error, resp) => {
if (error) throw new Error(error);
resp.status.map(val => {
if(val.key == "data"){
setProjectvalue({...projectvalue, [projectName] : val.actualValue })
}
})
}
)
});
, []);
See official React Docs https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
Upvotes: 1