I have jsfiddle Link https://jsfiddle.net/ilikeflex/r2uws1ez/30/
I am trying to set new state by accessing the previous state. I have three different cases where i am trying to update the state but i am not sure why does Case2 and Case 3 does not work. Can you please help me ??
const useState = React.useState;
function Example() {
const [todos, setTodos] = useState([
{id:1,text:'Learn React'},
{id:2,text:'Learn TypeScript'},
{id:3,text:'Learn Java'}
]);
const case1 = () => {
const newItem = {id:3,text:'Learn C '};
setTodos((prevState) => {
return prevState.concat(newItem);
});
}
const case2 = () => {
const newItem = {id:3,text:'Learn .Net'};
setTodos((prevState) => {
prevState.push(newItem); // I am adding to previous state and returning it
return prevState;
});
}
const case3 = () => {
const newItem = {id:3,text:'Learn C#'};
setTodos((prevState) => {
let result = { ...prevState, newItem }; // using spread operator
return result;
});
}
return (
<div>
<button onClick={case1}>Case 1</button>
<button onClick={case2}>Case 2</button>
<button onClick={case3}>Case 3</button>
<ul>
{todos.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'))
CodePudding user response:
To make case 2 work, you need to make a variable out of the prevState first. Then you can push to it and return that new variable.
const case2 = () => {
const newItem = {id:3,text:'Learn .Net'};
setTodos((prevState) => {
const newState = [...prevState]
newState.push(newItem);
return newState;
});
}
For case 3, you made a little mistake by making result an object instead of an array. Change the {}
to []
and it should work fine, like this.
const case3 = () => {
const newItem = {id:3,text:'Learn C#'};
setTodos((prevState) => {
let result = [...prevState, newItem ] ;
return result;
});
}
CodePudding user response:
In all the cases new array need be created and returned.