I want you to help me with something that doesn't work well for me, what happens is that I want to add a data in an array through a function but instead of adding it, it overrides it, I don't know what is wrong in redux:
const [list,setList]=useState([])
const addList=(id)=>{
setList([id])
}
CodePudding user response:
I think you want something like this, which appends id
to the list
array:
const [list,setList]=useState([])
const addList=(id)=>{
setList([...list, id])
}
CodePudding user response:
First you need to add an element not override the whole array with another one. Second in react useState variable you should use the previous value to update the new array. You can't use the list itself. Try this:
const [list,setList]=useState([])
const addList=(id)=>{
setList(pre => [...pre, id])
}
Or you can use this (it's in old javascript way):
const [list,setList]=useState([])
const addList=(id)=>{
let newList = list
newList.push(id)
setList(newList)
}
CodePudding user response:
When you update a React state property (like your list
) using its previous value,
you should use the callback argument of setState.
The reason is that state updates may be asynchronous in React (https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)
const [list,setList]=useState([])
const addList=(id)=>{
setList(list=> list.concat(id));
// or setList(list=> [...list, id]);
})
}