2

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
        },
    ]
  })
1
  • Is this array a part of some kind of data? Commented Jun 6, 2022 at 21:35

1 Answer 1

3
  • 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>
  );
}

Sign up to request clarification or add additional context in comments.

2 Comments

a working sandbox can be found this link
Thanks for the answer, I think it works with useEffect hook

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.