Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an array in React using Hooks

I'm trying to figure out the working of React Hook API. I'm trying to add a number to a list. The code that I commented, i.e myArray.push... doesn't seem to perform the operation, though the code below it is working fine. Why is it so?

import React, {useState} from 'react'

export default () => {

  const [myArray, setArray] = useState([1,2,3])

  return (
    <div>
      {myArray.map((item=>{

        return <li>{item}</li>

      }))}
      <button onClick = {()=>{

        // myArray.push(myArray[myArray.length-1]+1)
        // setArray(myArray)

        setArray([...myArray, myArray[myArray.length-1]+1])

      }}>Add</button>
    </div>
  )
}
like image 833
Jithin Ks Avatar asked Feb 19 '19 15:02

Jithin Ks


People also ask

How do you update an array in React hook?

myArray. push(1); However, with React, we need to use the method returned from useState to update the array. We simply, use the update method (In our example it's setMyArray() ) to update the state with a new array that's created by combining the old array with the new element using JavaScript' Spread operator.

How do you add items to an array in React hooks?

Recap: How to add to an array in state By mastering the wrapper function, I finally solved my problem of how to add to an array in React state in three easy steps: Use useState([]) Hook to set state to [] and get state setter function. Pass wrapper function to state setter function (as a call-back function)


1 Answers

I would recommend using useReducer for anything more complicated than a single value.

function App() {
  const [input, setInput] = useState(0);

  const [myArray, dispatch] = useReducer((myArray, { type, value }) => {
    switch (type) {
      case "add":
        return [...myArray, value];
      case "remove":
        return myArray.filter((_, index) => index !== value);
      default:
        return myArray;
    }
  }, [1, 2, 3]);

  return (
    <div>
      <input value={input} onInput={e => setInput(e.target.value)} />
      <button onClick={() => dispatch({ type: "add", value: input})}>
        Add
      </button>

      {myArray.map((item, index) => (
        <div>
          <h2>
            {item}
            <button onClick={() => dispatch({ type: "remove", value: index })}>
              Remove
            </button>
          </h2>
        </div>
      ))}
    </div>
  );
}
like image 73
K.. Avatar answered Oct 16 '22 20:10

K..