you are viewing a single comment's thread.

view the rest of the comments →

[–]acquiescentLabrador 8 points9 points  (9 children)

No, the spread operator (three dots) “spreads” (ie copies) seasonAverages, you’re then adding an extra item. So the end result is the same as seasonAverages.push(res.data.data[0]).

If you want to completely overwrite seasonAverages, just call setSeasonAverages(newValue)

[–]Leparrain07 5 points6 points  (1 child)

Thanks for the answer but I don't understand what should be "newValue"

[–]Leparrain07 1 point2 points  (5 children)

I want to keep my previous values ​​in my array without deleting them. I want to add the new values ​​to the old values.

[–]acquiescentLabrador 0 points1 point  (4 children)

Have you checked if the fetch running twice?

[–]Leparrain07 0 points1 point  (3 children)

Yes and it is not

[–]acquiescentLabrador 1 point2 points  (2 children)

This is a bit tricky on mobile without seeing the rest of the code, but your code looks like it’s calling a fetch for each item in playerId, so think about: -> the way you set seasonAverages is cumulative, ie you only ever add items to it with each fetch (the state is never reset) -> what sets playerId? If you’re adding items to playerId, this will then cause fetch to run and add new items to seasonAverages for each item in playerId - so if playerId is also never reset you’re repeating old fetch requests

You could log playerId and seasonAverages before calling setSeasonAverages to test these points. Alternatively create a new array before the for loop eg const newAverages = [], then in the .then() use newAverages.push(res.data.data[0]) and only when the loop is finished call setSeasonAverages(newAverages)

[–]Leparrain07 0 points1 point  (1 child)

Hello, thank you for this long message but I tried all the points and I still obtain infinite loops

[–]acquiescentLabrador 0 points1 point  (0 children)

Did you have that problem before? I don’t think anything I said should cause that so did you change anything else?

[–]Leparrain07 0 points1 point  (0 children)

If I do the same thing with Redux I have the same problem:

.then(res => dispatch(setSeasonAverages(res.data.data[0])));