0

I am trying to update my array state with a list of records I am getting from an API, I am trying it as follows:

  const [record, setRecord] = useState([])

  const addRecords= async ()=>{
     const apiResult = await apicall()

     setRecord(record.length ? [...apiResult, ...record] : apiResult)
}

however every time the api is called is overwritting my 'record' with the last items added from the api instead of putting them together.

I also tried using .concat() with same result

const addRecords=async()=>{
   const apiResult = await apicall()

   setRecord(record.concat(apiResult ? apiResult:[])
}

there is sth here I am not managing to understand, hope someone can clarify what can it be.

Jgarnie
  • 431
  • 6
  • 20
  • 1
    Try with `setRecord(record => [...apiResult, ...record])` – adiga Jun 14 '21 at 11:11
  • Can you show more of your code? How are you calling addRecords? – Tushar Shahi Jun 14 '21 at 11:17
  • excellent!, it is working now, thank you very much!, funny thing is that I also tried with prevState before but was not spreading the arrays, so the result was not working as well, thanks again for your answer, it definetly works as expected, you can put it as an answer so I can accept it and others with same problem will find it easier – Jgarnie Jun 14 '21 at 11:17
  • 1
    You probably have this code inside `useEffect` and it takes closure over the initial `record`. And `useEffect` doesn't run on re-render. This issue: [State not updating when using React state hook within setInterval](https://stackoverflow.com/questions/53024496) – adiga Jun 14 '21 at 11:20

1 Answers1

1

I think you want to use a function in your setter to get your previous value (I dont understand enough to give you the reason why, but I think it has something to do with your record being a frame or two out of date)

const addRecords=async()=>{
   const apiResult = await apicall()
   //prevRecord is more recent than record (I think)
    setRecord(prevRecord=>prevRecord.concat(apiResult || []) 
}

PhantomSpooks
  • 2,877
  • 2
  • 8
  • 13