Home > front end >  How to remember the state, after I reload the page or I go to another componenet?
How to remember the state, after I reload the page or I go to another componenet?

Time:02-17

I'm trying to remember the state after the user adds a new field with an add button to the component and writes a word in the input.

AddFeild.js

export default class AddField extends React.Component {

  
  constructor(props) {
    super(props);
    
    this.state = {
      userName: "",
      users: [],
    };
  }
  

  handleClick() {
    var userName = this.state.userName;

    items.push(this.state.users);

    this.setState({
      users: users,
      userName: "",
    });
  }

  updateUsers(event) {
    this.setState({
      users: event.target.value,
    });
  }


render() {
  return (
         <div className="flex justify-center py-8">
               <button className="btn-main" onClick={this.handleClick.bind(this)}>
            Add a User
          </button>
);
}

In this component, when I click the Add a User button it shows an empty field(to put the name of the user). I put the name Jimmy(exp) in the input but I don't save or cancel it. What I'm trying to do is to go to another component or to reload the page and then go to AddField.js page, I want the name Jimmy to be there, even though I didn't save the name, or cancel the changes. How can I do it?

CodePudding user response:

you could store the name state in localstorage and fetch it back on component loading

CodePudding user response:

For a piece of state to persist through navigation you would need to implement some sort of global state(Context, Redux, etc.)

To keep that data after a hard refresh you would need to either setup something like redux-persist or save to localstorage

CodePudding user response:

you can use the package react-persist

npm i react-persist

find more info on this package at https://www.npmjs.com/package/react-persist

  • Related