In my Nextjs web application, one of my pages has two functions that allow for emails to be added or removed from an array using nextjs’s useState().
const [invites, setInvites] = useState([])
// other code
const lmao = () => {
console.log(invites)
}
const addEmail = async (email) => {
if(!invites.includes(email)) {
setInvites([...invites, email])
}
lmao()
}
const removeEmail = async (email) => {
let tempArray = invites
const index = tempArray.indexOf(email)
if(index > -1) {
tempArray.splice(index, 1)
}
setInvites(tempArray)
lmao()
}
The function addEmail
successfully results in a component rerender, and when ran, will visibly update the page with the added email. However, the function removeEmail
fails to rerender the page. I used the function lmao()
to see that invites
was indeed being changed as needed, the page just was not rerendering to display the change.
I have also looked at Why does setState([…arr]) cause a rerender but setState(arr) does not?, and it does not answer my question because in my case, the item passed into the mutator is not ===
to its previous value, unless I am missing something. Does anyone know why this is?