Home > front end >  Push method in useState hook || REACT NATIVE
Push method in useState hook || REACT NATIVE

Time:11-03

I have an array of items in a state variable like this.

const [items, setItems] = useState(["item1", "item2", "item3")])

How to replace one item in the array. Below is the method I have used to get it done.

{
    let dummy = [...items]
    dummy[1] = "items 1.1"
    setItems(dummy)
}

But, I am thinking that this is not at all the right way to do this.

Is there any other simplified way to solve this? Thanks in Advance

CodePudding user response:

Or you can use slice

const idxToChange = 1
setItems([items.slice(0, idxToChange), "items 1.1", items.slice(idxToChange 1, items.length)])

A good explanation of slice https://www.w3schools.com/jsref/jsref_slice_array.asp

CodePudding user response:

Your solution is not wrong, but I would add an extra check to make sure that items array contains an element which you wish to change.

let dummy = [...items]

if(typeof dummy[1] == 'undefined') {
    // does not exist
}
else {
    // does exist
    dummy[1] = "items 1.1"
}
setItems(dummy)

CodePudding user response:

Heres another way to do it. I don't know it's cleaner for you or not.

 setItems(items=> items.map((item,idx)=> idx===0?"items 1.1":item));
  • Related