1

How to update an array in react using prevState?

I want to insert a record into the array.

I found an information that should not be used to push for state preservation measure.

this.state = {
            dados : {
                doc: '',
                infe: '',
                bene: '',
                inco: [],
                cino: [],
            }
        }

this.setState(prevState => ({ dados:{
                inco: [...prevState.dados.inco, URL.createObjectURL(result)]
            }}))

this.setState(prevState => ({ dados:{
                cino: [...prevState.dados.cino, URL.createObjectURL(result)]
            }}))
3
  • what is the error message you are getting? Commented Apr 29, 2018 at 7:03
  • Cannot convert undefined or null to object Commented Apr 29, 2018 at 7:09
  • Is result variable appropriate? Plus i think your dados state variable is getting overwritten in first setstate function Commented Apr 29, 2018 at 7:10

2 Answers 2

3

Try to club the setstate() function call into one, as dados state key might lose other properties, hence it cannot find cino object in second setstate(). Here dados state object was getting only inco property after first setState() function call, hence now below code we are making sure consistency in state object is maintained

Here is sample code

 this.state = {
            dados : {
                doc: '',
                infe: '',
                bene: '',
                inco: [],
                cino: [],
            }
        }

this.setState(prevState => (
                 { 
                    dados:{
                            ...prevState.dados,
                            inco: [...prevState.dados.inco,
                                    URL.createObjectURL(result)
                                  ],
                            cino: [...prevState.dados.cino,
                                    URL.createObjectURL(result)
                                  ]
            }}))
Sign up to request clarification or add additional context in comments.

1 Comment

Its Work. Thank You Very Much!
0
 var exp = Object.assign([],data.questions);

   exp[index] = {
                 name:name,
                 question:question,
                 [event.target.name]:event.target.value
  }
   setData({
              ...data,
              questions:exp
   })

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.