+ 1
React UseState Hooks
How should I update the previous values in useState e.g const [value, setValue] = useState([ { title : "React Hook" } ]); I want To update the title in the useState how can I do
15 ответов
+ 7
cons updateInIndex = (index, data) => {
// index: index in the array
// data: the updated object that should replace the data in the given index
const newData = value.slice();
newData[index] = {...newData[index], ...data};
setState(newData);
}
+ 3
If value is an array,
To add another element in value
setValue([...value, {title: 'Another text'}]);
Or to overwrite the existing element
setValue([{title: 'Another text'}]);
+ 1
Use the setValue() function to update the state later.
Like so :
setValue(...value, {title: 'Another text'});
Edited:
setValue([...value, {title: 'Another text'}]);
This will add another element to the value state.
+ 1
Arb Rahim Badsa 😄😄 I know that's easy but I don't want to add another title I want To update the previous title
Like setState in classes
+ 1
Arb Rahim Badsa I think you are almost there.
It should be setValue({ ...value, title: 'Another text' });
Or more proper way is
setValue( v => { ...v, title: 'Another text' });
+ 1
Saad Mughal you might added extra [] on useState.
It should be
const [value, setValue] = useState({
title : "React Hook"
});
Unless you really want to set value as a single element array.
+ 1
Calviղ I actually thought, as it is an array, '...value' will include all the existing elements and passing an object as the second parameter will add another object in the state. Really thanks for the clarification!
0
Saad Mughal
Arb Rahim Badsa 's way is not add another title, it's update the existing title.
Read more on spread operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
0
Saad Mughal Oh, lol I got it wrong. 😅
0
Arb Rahim Badsa No problem
But confusing
You said you got it wrong
And cavin say you are right
😐
0
OK let me try It thanks for your help guys
0
Calviղ yes I am also thinking about overwrite the previous object and try To implement it
Thanks for your help If it's work I will tell you
0
Some one suggest that
Use spread operator to copy the state into new variable and then change that variable and by using setvalue pass new array to it
0
This syntax also works for me
let newValue = [...value];
newValue. map(ob => {
ob.title = "new title"
)
setValue(newValue):