New to React and async stuff on javascript, and have looked through a few similar questions on StackOverflow
- Can I set state inside a useEffect hook
- Is useState synchronous?
- React Hook useEffect issue with setState
Here's my useEffect. I'm doing a fetch (in getPieData), using the response to set investment's state (it returns an array), then using investment's new value to set the state of funds (looping through the array). I run console.log and see that the value does exist, but when I run setFundslist and then later map its value in a component, I get undefined is not a function. Setting investment earlier works, so I'm wondering if it's the for loop itself and something to do with asynchronosity that is causing me problems.
React.useEffect(() => {
getPieData().then(response => {
setInvestment(response);
return response;
})
.then((investmentResponse) => {
const funds = []
for (var i = 0; i < investmentResponse.length; i++) {
funds.push(investmentResponse[i])
}
return funds
})
.then(funds => {
setFundsList(funds)
console.log(funds)
})
}, []);
Then in my component, at the asterisked line, I get the following error: TypeError: undefined is not a function (near '...funds.map...')
export default function Table({ fundsList }) {
const [funds, setFunds] = React.useState([]);
React.useEffect(() => {
**********setFunds(fundsList.map(strat => ({***************
gainToday: "0.00%",
title: strat,
gainOverall: "0.00%"
})).then(console.log(funds))
}, []);
return(
{funds.map(fund => (
// some stuff
<tr key={fund.title}>
// some stuff
))}
)
}