Home > Enterprise >  How to maintain previous data and current data in react usestate in react-native or reactjs?
How to maintain previous data and current data in react usestate in react-native or reactjs?

Time:06-18

Currently i am learning reactjs. I want to store my previous data and upcoming 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

CodePudding user response:

It;s very easy. You can use my code snippet . With the help of this you can store your previous data and upcoming data as well .

Method : 1

const [arrayOfObjs, handleObjSelection] = useState([]);
// on a buttton for example
<button
  onClick={selectedObj => handleObjSelection(
              prevSelected => [...prevSelected, selectedObj],
          ))}
>

Method Second :

const [ store, setStore] = useState([]);
 .....

 setStore(...store, upcomingData);

Here Upcoming 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);

Happy Coding !!

CodePudding user response:

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>
  );
}
  • Related