0

I'm fetching data from Api, and then updating my state, but state is just holding last element of array, I'm using spread operator.

const Index=()=>{
    const [data, setData] = useState([]); //append new messages in this data
    const [keys, setKeys] = useState([]); //users ids will be stored in this state
    const fetchNewData = async allKeys => {
         for(let i=0;i<allKeys.length;i++){
             let newUserData=//fetching data from somewhere
             setData([...data,newUserData]) //now this fucntion is not setting state properly 
         }
    }
    //this useEffect is dependent on **teacher** state
    useEffect(() => {
       let tempKeys = Context.teacher.map(item => item.id);
       fetchNewData(tempKeys);
       setKeys(tempKeys);
    }, [Context.teacher])
    //this useEffect is dependent on **data** state
    useEffect(() => {
       console.log('data has been set: ', data); //just single user is logged everytime
    }, [data]);
    return **jsx**
}
export default Index;
  • What do you mean by `not setting properly` and try to print the `newUseData` if it's working? – Rohit Aggarwal Jun 20 '22 at 13:19
  • @RohitAggarwal yes, I printed newUserData which is totally fine, the issue arises when I set "data" state using "setData()", it is not copying previous data, it is just setting newUserData while previous data is losing... – Faizan Muhammad Jun 20 '22 at 14:08
  • So it keeps only the last user data? – Marat Jun 20 '22 at 14:09

1 Answers1

0

updating array(state) like this works for me:

setState(oldValue=>[...oldValue,newValue])