1

when running my reducer dispatch method here:

function reducer(state, action) {
    switch (action.type) {
  
 case "updateBox":
    return     state.map((input, index) => {
     input.map((data, NextIndex)=>{

if (action.NextIndex === NextIndex) { data.comment = action.text } else {data.comment = data.comment}
     })       
        });
     

the deve tools shows that regardless of if the action.Nextindex = NextIndex the data.comment will always be changed to the action.text.

other code:

let object = {
    comment:""
}
let box = [object, object]
let list = [box, box]



 const [listState, listDispatch] = useReducer(reducer, list);

      { listState.map((data, index)=> (
{data.map((input, NextIndex)=>(


        <TextField value={data[NextIndex].comment} 
        onChange={(e)=>{listDispatch({type:"updateBox", text:e.target.value, field:"comment", NextIndex, index})}}
multiline fullWidth variant="outlined"/>


)})}

sandbox link

https://codesandbox.io/s/charming-sid-wdn0h?file=/src/App.js

Alexander Hemming
  • 753
  • 1
  • 6
  • 28

1 Answers1

0

Just because the variable is not in the React state does not mean it is copy by value.

When each variable is changed then the other variables are also changed.

better would also be to replace the mapped aspect as this:

  let stateCopyr = [...listState];
    stateCopyr[action.index][action.NextIndex].comment = action.text
    console.log(stateCopyr)
    console.log("update")
    return stateCopyr  
Alexander Hemming
  • 753
  • 1
  • 6
  • 28