Home > Software design >  Adding to a state array without the resulting array being read only, in React Native?
Adding to a state array without the resulting array being read only, in React Native?

Time:01-12

Im programming a component where I am mapping over a component using an array I have stored in state.

const [animalList, setList] = useState(['cat', 'dog'])
 {  animalList.map((tag) => {
     return (
        <AnimalButton animalz={tag}/>
      )
   })
 }

I want to add to the state array to force to make the app rerender. I attempted to do so with a .push function, store the increased array in a temporary variable and assign that new array to the state, as push() and unsplice don't return the actual array.

 onSubmit={(values, actions) => {
                    actions.resetForm();
                   animalList.push(values.pet)
                   let newList = animalList
                    setList(animalList = newList)
                 }}

However I get this error [TypeError: "animalList" is read-only]?

Is there a way to change add to animalList without my resulting list in the state becoming read only?

CodePudding user response:

Yes you cannot push this into const. However, you can use this approach.

setList([...animalList,values.pet])
  •  Tags:  
  • Related