1

I am trying to push an item to an array in the state but it is not working. Here is my code.

const [features, setFeatures] = useState(['']) const addFeature = (event)=>{ event.preventDefault(); let featuresClone = features; featuresClone.push(''); setFeatures(featuresClone); console.log(featuresClone, fetaures); } 

This is the function which updates the state. In the log here features is updated. but, when I do a useEffect like this,

useEffect(()=>{ console.log(features) },[features]) 

It will not log the features which means features is not updated.

What am I doing wrong?

3 Answers 3

3

You can access the prev state and update the state like below,

const addFeature = (event)=>{ event.preventDefault(); setFeatures(prev => [...prev, '']); } 
Sign up to request clarification or add additional context in comments.

Comments

3

Don't mutate state directly, do this instead:

const addFeature = (event)=>{ event.preventDefault(); let featuresClone = [...features]; featuresClone.push(''); setFeatures(featuresClone); console.log(featuresClone, fetaures); } 

2 Comments

Thanks it worked, Can you explain why my approach did not worked?
when you did let featuresClone = features; it actually does not creates a new array, its just creates a new reference to the original state, and in react mutating the state directly is not allowed. In the above answer, when we do let featuresClone = [...features]; then the new array having the same element as that of features gets created which then can be used to set the state.
1

Your featuresClone is not a clone but the same list, because unlike primitive integers lists are passed by reference and not by value.

use: let featuresClone = [...features,'']; to clone it and add the value

so you can also avoid featuresClone.push(''); since with [].push it might happen that you modify a list that has only been passed on by reference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.