Currently i am learning reactjs. I want to store my previous data and uping data in usestate . IS there any trick for that ?
For example : Firstly i input "A" after that i input "B". I want A and B are stored in usestate even when i add new data in it
Currently i am learning reactjs. I want to store my previous data and uping data in usestate . IS there any trick for that ?
For example : Firstly i input "A" after that i input "B". I want A and B are stored in usestate even when i add new data in it
Share Improve this question asked Jun 18, 2022 at 11:47 TaehyungTaehyung 531 silver badge5 bronze badges2 Answers
Reset to default 3It's very easy. You can use my code snippet. With the help of this you can store your previous data and uping data as well.
Method 1:
const [arrayOfObjs, handleObjSelection] = useState([]);
// on a buttton for example
<button
onClick={selectedObj => handleObjSelection(
prevSelected => [...prevSelected, selectedObj],
))}
>
Method 2:
const [ store, setStore] = useState([]);
.....
setStore(...store, upingData);
Here Uping Data is the data which you want to add in the useState. It can be store as well. Like:
const [ store, setStore] = useState([]);
.....
setStore(...store, store);
I would use object state for this then you can keep both state. Here is the working version https://codesandbox.io/embed/frosty-bird-hg3izs?fontsize=14&hidenavigation=1&theme=dark
import { useState } from "react";
export default function App() {
const [obj, setObj] = useState({previous: '', current: ''})
const handleChange = (e) => {
setObj({previous: obj.current, current: e.target.value})
}
return (
<div className="App">
<input value={obj.current} onChange={(e) => handleChange(e)} />
<p>I am previous {obj.previous} </p>
<p>I am current {obj.current} </p>
</div>
);
}