I am having difficulty getting a mapped fetch function to run inside a useEffect
.
I currently have a useEffect
that runs a function. First it obtains data from a fetch request and then it must map
a fetch function on that data to update it array by array.
useEffect
:
useEffect(() => {
fetchData('')
}, [])
first it fetches data from an API and then within the same function it performs some recalculation:
const fetcData = async (time) => {
fetch(`http://...`, {
method: 'POST',
body: JSON.stringify({ //converts body to json
time: time
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}).then(res => res.json())
.then(res => {
setA(res.data.a);
setB(res.data.b);
const recalcData = recalculateData(res.data.c)
setCopyOptions(recalcData)
setDataLoaded(true);
})
.catch(err => {
console.log(err)
setDataErr(true)
})
}
The recalculation step is done here:
const recalculateData = (data) => {
let tempCopy = JSON.parse(JSON.stringify(data))
copyOptions.map((item, ix) => (
fetch(`http:...`, {
method: 'POST',
body: JSON.stringify({ //converts body to json
data: data[ix]
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}).then(res => res.json())
.then(res => {
tempCopy[ix].a = res.a
tempCopy[ix].b = res.b
tempCopy[ix].c = res.c
})
))
return tempCopy
}
I am also using this recalculateData function elsewhere. It works fine when I trigger it from a button but it doesn't trigger inside useEffect
. I'm not an expert on async functions so any pointers will be greatly appreciated.