dud3
dud3

Reputation: 145

How to change array completely with a new array in React.JS with useState?

I've been searching everywhere to find this but all the answers are about just adding new items to an array with useState.

So imagine I have an array like this

    [
        {
          id: 1,
          title: 'take out trash',
          done: false
        },
        {
          id: 2,
          title: 'wife to dinner',
          done: false
        },
        {
          id: 3,
          title: 'make react app',
          done: false
        },
    ]
  });

Now I want to change it with a completely new array by using useState.

Like,

{
    [
        {
          id: 5,
          title: 'X',
          done: true
        },
        {
          id: 8,
          title: 'Y',
          done: true
        },
        {
          id: 9,
          title: 'Z',
          done: true
        },
    ]
  })

Upvotes: 2

Views: 1096

Answers (1)

omar
omar

Reputation: 536

  • first initialize the new array :
export default function App() {
  const newArray = [
    {
      id: 5,
      title: "X",
      done: true
    },
    {
      id: 8,
      title: "Y",
      done: true
    },
    {
      id: 9,
      title: "Z",
      done: true
    }
  ];
  ...
  • then:
    1- import useState and useEffect from React
    2- initiate your state
    3- set your to the newArray inside the useEffect function
    4- map your state array and return it to test
import { useEffect, useState } from "react";

export default function App() {
  const newArray = [
    {
      id: 5,
      title: "X",
      done: true
    },
    {
      id: 8,
      title: "Y",
      done: true
    },
    {
      id: 9,
      title: "Z",
      done: true
    }
  ];
  const [data, setData] = useState([]);
  useEffect(() => {
    setData(newArray);
  }, []);
  return (
    <div>
      {data
        ? data.map((o, i) => <div key={i}> title: {o.title} </div>)
        : "loading..."}
    </div>
  );
}

Upvotes: 3

Related Questions