I have an state obj like.
state = [
{car: "merc"};
{car: "ferrari"};
]
now when user clicks the reset button. I want to update the state to
state = [
{car: ""};
{car: ""};
]
setState(x=> [...x, {car: ""}]);
but this pushes a new object I don’t want o add new obj I want o update the existing one.
How can I achieve this using useState hook in react js?
setState of React useState hook replace state instead of merging it like this.setState.
So you can simply write
setState([{car:""}, {car:""}]);
Hope this helps.
p/s: remember to replace the semi-colons between your objects with commas if they are in your source code too
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.

Welcome, deepak.
You should be working on your state variable outside of the setState
function. So, create a new array with your “reset” state, and pass that to setState
.
Hope this helps
Thanks for the reply !
But i trying to achieve this using spread operator rather than directly setting the state.
Can any one provide and syntax how to do this if I have n number of objects in my array?
Thanks for the reply !
But i trying to achieve this using spread operator rather than directly setting the state.
Can any one provide and syntax how to do this if I have n number of objects in my array?
@deepak.p8412
First, let me ask do you know what a spread operator does?
A spread operator takes an object and spread its key, like so.
let obj1 = {name:"John", age:25};
let obj2 = {...obj1, hobby:"eating"};
If you write the above, the spread operator takes the key of obj1, and add it to obj2. So your obj2 will be
{name: 'John', age:25, hobby:'eating'}
which is “pushing” new key-value pair to the original object.
So in other words, using spread operator fundamentally means you want to push new values. Since you explicitly say that your app ‘pushing new value to state’ instead of ‘replacing it’ is your problem, it makes no sense to use spread operator at all.
The opposite of directly setting the state is using function to set the state. You do that when your new state depends on your old state, and that has nothing to do with spread operator.
Thanks a lot for your response.
I thought that I could achieve the same using spread operator but understood now.
To confirm my approach I have written a for loop and then updating the state.
var newArray = [...myArrayState];
for(i=0;i< myArrayState.length; i++){
myArrayState[i].obj1 = "";
myArrayState[i].obj2= "";
}
setState(myArrayState);
Can you please confirm if this is the right approach or not?
Or if there’s any better approach available with less syntax please let me know.