0

I am trying to clone array to functional state using following code. But after setting state to new array i am still getting null array

const [tarFileList, setTarFileList] = React.useState([]); 

const updateTarFileList=(res)=>{
    let list=[];
    res.forEach(element => {
        list.push(element);
    });
    setTarFileList(list);
}
  • this seems to be fine, did you check the state in the dev tools ? – Sudhanshu Kumar Jun 17 '20 at 07:33
  • can you share the complete code? Because this looks fine, maybe the problem is from where you are calling this function and where you are using the updated state. – Manish Sundriyal Jun 17 '20 at 07:33
  • i used console.log to print the updated state but i am getting null array – Divyansh Gupta Jun 17 '20 at 07:35
  • @DivyanshGupta - state is updated asynchronously so you should instead log the `list` to ensure that it's not empty. – Ramesh Reddy Jun 17 '20 at 07:36
  • Can you tell us what a `nu` is? I don't see you using `tarFileList` anywhere so how do you know it's the same? My guess is that you are trying to access a [stale closure](https://dmitripavlutin.com/react-hooks-stale-closures/). React hooks are not magic and normal closure scope still applies. – HMR Jun 17 '20 at 07:36
  • Are you sure there's something inside `res` argument. Can you log `res` in the console and let us know – thealpha93 Jun 17 '20 at 07:37
  • @Ramesh I did check the list its not empty. – Divyansh Gupta Jun 17 '20 at 07:40
  • @TheAlpha93 I checked res and list values. It is not empty – Divyansh Gupta Jun 17 '20 at 07:44
  • @DivyanshGupta - Okay, then your state is being properly updated. Try to log it in `useEffect` hook. Check [this](https://stackoverflow.com/a/62410116/9765167) – Ramesh Reddy Jun 17 '20 at 07:45
  • @DivyanshGupta `i am still getting null array` That is impossible because you initialise it with an empty array and set it to list in `updateTarFileList`, it is never null. – HMR Jun 17 '20 at 07:59
  • The problem is solved. The state is already being updated. I was checking the value using console.log which was wrong idea. The correct method is useEffect. Thanks @Ramesh, thanks all – Divyansh Gupta Jun 17 '20 at 08:06

0 Answers0