0

I am trying to set a value to the value of context/state but it is updating the contaxt/state value instead. As you can see below, I am setting newParticipants equal to the array of global.participants, then when I click the button, it takes the value of that button and pushes it to the newParticipants array. For some reason it is updating global.paricipants as if I were calling setGlobal. What am I missing? I am not trying to update the context.

const { global, setGlobal } = useContext(GlobalContext);

let newParticipants = global.participants;
const click = (event) => {
    newParticipants.push(event.currentTarget.attributes[1].value);
    axios.put(
        "http://localhost:8080/update/participants",
        { old: global.participants, new: newParticipants },
        {
        headers: { authorization: "Bearer: " + localStorage.getItem("Auth") },
        }
    );
};
B_HOP
  • 27
  • 4

1 Answers1

0

You are mutating the original array as you are referencing the same array after assigning it to newParticipants, you should instead clone the participant list before updating it

const { global, setGlobal } = useContext(GlobalContext);

// shallow clone the list
let newParticipants = [...global.participants];
const click = (event) => {
    newParticipants.push(event.currentTarget.attributes[1].value);
    ... 
};
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400