yongchang
yongchang

Reputation: 522

How can I prevent my array from being overwritten when setting the state?

What I am trying to do: I want to add all elements into my array

Actual result: My array is being overwritten

As seen from my codesandbox, the output should be helloworld, but it is only showing world.

Parent.js

import "./styles.css";
import { useState } from "react";

import Child from "./Child";

export default function Parent() {
  const [arr, setArr] = useState([]);

  return (
    <div className="App">
      <Child setArr={setArr} />
      {arr}
    </div>
  );
}

Child.js

import { useEffect } from "react";

export default function Child(props) {
  useEffect(() => {
    props.setArr("hello");
    props.setArr("world");
  });
  return (
    <div className="Child">
      <h1>This is child componemnt</h1>
    </div>
  );
}

This is my codesandbox link

Upvotes: 0

Views: 126

Answers (1)

javascwipt
javascwipt

Reputation: 1178

You overwriting your array with a string, the trick is to create a shallow copy of your value and mutate the new copy. and then set the state afterwards:

import "./styles.css";
import { useState } from "react";

import Child from "./Child";

export default function Parent() {
  const [arr, setArr] = useState([]);

  return (
    <div className="App">
      <Child setArr={setArr} arr={arr} />
      {arr}
    </div>
  );
}

import { useEffect } from "react";

export default function Child(props) {
  useEffect(() => {
    const nextArr = [...props.arr];
    nextArr.push("hello", "world");
    props.setArr(nextArr);
  }, []);
  return (
    <div className="Child">
      <h1>This is child componemnt</h1>
    </div>
  );
}

Upvotes: 1

Related Questions