Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I want to update my array in useSate in React Hooks then its working but the array is grow every times why?

import React,{useState} from "react";

const friendsArray = [
    {
        name:"Lalit",
        age: 23,
    },
    {
        name:"Neha",
        age: 22,
    },
    {
        name:"Piyush",
        age: 20,
    },
]


function Arrex(){

    const [arr,setArr] = useState(friendsArray)

    const handleclick=()=>{
        setArr((prevArr)=>[
        ...prevArr,
        {
            name:"Shubham",
            age:25,
        }])
    }
    const handleupdate=()=>{
        setArr([
            ...arr,
            arr[0].name="Purohit",
            arr[1].name="Sharma",
        ],
        )
    }



    return(
        <div>
            <h2>Adding a new value to array</h2>
            <ul>
                {arr.map((friend,index)=>(
                    <li key={index}>name: {friend.name}<br/>age: {friend.age}</li>
                ))}
            </ul>
            <button onClick={handleclick}>Add New</button>
            <button onClick={handleupdate} >Update</button>
        </div>
    )
}

export default Arrex;

[Result After click on update ]
[Result Before click on update]

I am a new learner of react js and i was practices that concept for better understanding but when i update the array the output is get but the null object is increases by two i try many time but not solve the issue i to get the proper output in this code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Working codesandbox

Problem with handleupdate function. If you want to update a specific element in an array, you must use the setArr method correctly.

import React, { useState } from "react";

const friendsArray = [
  {
    name: "Lalit",
    age: 23,
  },
  {
    name: "Neha",
    age: 22,
  },
  {
    name: "Piyush",
    age: 20,
  },
];

function Arrex() {
  const [arr, setArr] = useState(friendsArray);

  const handleclick = () => {
    setArr((prevArr) => [
      ...prevArr,
      {
        name: "Shubham",
        age: 25,
      },
    ]);
  };

  const handleupdate = () => {
    // Update specific elements in the array
    setArr((prevArr) => [
      {
        ...prevArr[0],
        name: "Purohit",
      },
      {
        ...prevArr[1],
        name: "Sharma",
      },
      ...prevArr.slice(2), // Keep the rest of the array unchanged
    ]);
  };

  return (
    <div>
      <h2>Adding a new value to the array</h2>
      <ul>
        {arr.map((friend, index) => (
          <li key={index}>
            name: {friend.name}
            <br />
            age: {friend.age}
          </li>
        ))}
      </ul>
      <button onClick={handleclick}>Add New</button>
      <button onClick={handleupdate}>Update</button>
    </div>
  );
}

export default Arrex;

Changed the logic in the handleupdate function to correctly update certain elements in the array. It preserves the properties of the first two elements (names in this case) and updates them accordingly, but the rest of the array remains unchanged. This allows you to update specific elements within React’s arr state.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading