0

i have a state(array of object) which is as follows:

 const [state,setstate]=useState({picture:'',name:'',job:''})

and i have 3 inputs in Front-end side which get picture,name,job... i define an array to save a collection of objects (consisting of picture,name and job of each person) as follows:

 var colllection=[]

i use collection.push({state}) , but it overrides collection and does not add new state to end of the mentioned array.any idea?

5
  • can you add the full code, please, otherwise it's hard to help you Commented Sep 10, 2020 at 7:51
  • I have 2 ideas: 1) your var collections placed incorrectly and always reinitialized. 2) look at variable name - it contains 3 l Commented Sep 10, 2020 at 7:52
  • - just do it like this: collection.push({...state}) Commented Sep 10, 2020 at 7:57
  • you were pushing object, which still referenced to state, so changing in state object, will override the old values in collection Commented Sep 10, 2020 at 7:58
  • Do Not Modify State Directly Please go through the documentation one. here; reactjs.org/docs/… Commented Sep 10, 2020 at 8:13

1 Answer 1

1

For react state you need to replace the value rather than changing it.

So code something like this:

const [state, setstate] = useState([]);

const handleAddPerson = person => useState(prev => ([...prev, person]));

Where when we want to add a person we set the state to a new array that contains the contents of the original array plus the new object.

useState rather than being passed a new value can be passed a function which takes as an argument the previous value the state held and returns the new value for the state.

I'm used to syntactic sugar for creating a new array [...prev, person] this could be written in plain javascript as prev.concat([person]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.