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.
3
Answers
I think you are trying to update the name of the first two entries.
what you did with handleupdate is to update the original copy of the array and return the result of those updates to the setState, this is why you see two additional empty entries while the first two values remain unchanged, the return value of assignment has nothing to do with your arr instance.
What you should do instead, is to make a copy of the original array and update the value accordingly.
Working codesandbox
Problem with
handleupdate
function. If you want to update a specific element in an array, you must use thesetArr
method correctly.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.The spread syntax (…) is used to create a shallow copy of an array, but the usage here is incorrect.
You’re trying to update the name property of the first two elements in the array.
Here’s the corrected version:
This code snippet uses the spread syntax to create a shallow copy of the first two elements in the array (arr[0] and arr[1]), updating the name property for each. The rest of the array (starting from index 2) is included using the slice method. Finally, the updated array is passed to the setArr function.
Keep in mind that directly modifying the state in React is not recommended, so it’s better to create a new array with the desired modifications and then set the state with the new array.