So I've retrieved data in JSON
format using GET
request then I'm facing a problem in saving into my state
so that I can display them into my span
/div
/h1
using map function
. Here's how my JSON
data looks like:
[
{
"projectName": "SHIBA INU",
"projectToken": "SHIB",
"tokenPrice": 0.2,
"saleStart":{
"$date": "2021-12-20T20:00:00.00Z"
},
{
"projectName": "BITCOIN",
"projectToken": "BTC",
"tokenPrice": 200,
"saleStart":{
"$date": "2021-12-20T20:00:00.00Z"
}
]
So I'm trying to do this way but I dont think it will work:
const [projectData, setProjectData] = useState({})
useEffect(() => {
axios.get(`my api`).then(res => {
for(let i=0; i<res.data.length; i 1){
setProjectData(...projectData, res.data[i])
}
}).catch(e => console.log("error: ", e));
},[]);
I'm not sure whether I should save them into an array or an object
CodePudding user response:
I agree with @iLuvLogix comment: from the info in your example, it seems like you're trying to store an array of objects, so you'll want to initialize your state with an array, and then add the items from the response to the array as well. You also don't need the loop: you can spread all of the array items into a new array along with the existing state in one step:
const [projectData, setProjectData] = useState([]);
useEffect(() => {
axios.get(`my api`).then(res => {
setProjectData([...projectData, ...res.data]);
}).catch(e => console.log("error: ", e));
}, []);
CodePudding user response:
First of all you are not updating your i
value in your for loop. Since your i
value never will be less than res.data.length, it will loop infinitely.
Instead you should use i
to increment it at each iteration:
for(let i=0; i<res.data.length; i )
Other than that setting your state like that is problematic. setState
in React is async which means when you use it and access your projectData
it won't promise you that you are getting the updated state right away. Instead you should try to update your state at once in your case.
Also check Why is setState in reactjs Async instead of Sync?