0

I have a form that dynamically enters elements to a react state array on click, and obviously between clicks the state persists. I am trying to now do the same thing programatically but in each iteration the state does not persist, is the only answer to this truly a context object or local storage or is there something wrong with my iteration that I can correct to allow state to persist.

Ive simplified the code basically the button firing will add as many elements as I want but trying to tell react to create 3 elements via the for const only creates 1. I have scripts to write state to session storage, so if there's not some big thing i'm missing, I'll probably just do that, but i figure I'd ask and see cause it would drastically improve the overall health of my app if i knew the solution to this.

  const sectionI = {
    type: "i",
    sectionArea: "",
  };

const [i, setI] = useState([])

const strArr = ["i","i","i"]

const addI = () =>{
  const newI = [...i, {...sectionI}]
  setI(newI)
}

<button onClick={()=>addI()}>Add One Image</button>

const addMultiple = () =>{
   for(const el of strArr){
      const newI = [...i, {...sectionI}]
      setI(newI)
   }
}
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Mickey Gray
  • 440
  • 2
  • 11

1 Answers1

1

I will show you how to fix it and give you a link to another one of my answers for the explanation. Here is how to fix the issue:

const addMultiple = () =>{
   for(const el of strArr){
      setI(prevState => [
            ...prevState,
            {...sectionI},
          ])
   }
}

And here is why it is happening: https://stackoverflow.com/a/66560223/1927991

codemonkey
  • 7,325
  • 5
  • 22
  • 36