William Ferruzola
William Ferruzola

Reputation: 123

Add data in React object

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])
}

Upvotes: 0

Views: 1171

Answers (3)

Nice Books
Nice Books

Reputation: 1861

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]);
})
}

Upvotes: 0

Hossein hossein
Hossein hossein

Reputation: 147

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)
}

Upvotes: 1

Alan Friedman
Alan Friedman

Reputation: 1610

I think you want something like this, which appends id to the list array:

const [list,setList]=useState([])
const addList=(id)=>{
    setList([...list, id])
}

Upvotes: 0

Related Questions