SK1dev
SK1dev

Reputation: 1139

React: Permanently store user input as the value

I currently have the user input being updated by state and stored as the value however whenever the user directs to another page, closes the page or refreshes it, the value disappears. I want to permanently store the value there until the user changes their input. Would I need to use persistent state for this? How can I permanently store the value of the user input until the user changes it?

class Planning extends React.Component {
  constructor() {
    super()
    this.state = { 
      title: '',
      goal: '',
      tech: '',
      features: '',
     details: ''
       }

    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

handleChange(event) {

this.setState({ 
 [event.target.name]: event.target.value 
})
}

handleSubmit(event) {
  const {
    title,
     goal,
     tech,
     features,
    details
  } = this.state;
  event.preventDefault();
  this.setState({ title, goal, tech, features, details });
}

    render() {
      return (
        <form onSubmit={this.handleSubmit}>
        <div>
          <label className="label-title">
            Project Title:</label>
            <input name="title" id="title" type="text" value={this.state.title} onChange={this.handleChange} required aria-required="true"/>
            </div>        

Upvotes: 0

Views: 1376

Answers (3)

Bhupendra
Bhupendra

Reputation: 1286

Saving to localStorage is a synchronous operation , so we don't need to sync the local state to localStorage every time state variable changes as React already keeps the track of the application state in the user's session . You need to persist it in localStorage when user leaves page / refreshes. Save to localStorage on componentWillUnmount and window.onbeforeunload events. There is the a storage component that handles everything : https://github.com/ryanjyost/react-simple-storage

Upvotes: 0

Łukasz Karczewski
Łukasz Karczewski

Reputation: 1208

Change your handleChange function to:

handleChange(event) {
const { value, name } = event.target
localStorage[name] = value

this.setState({ 
 [name]: value
})
}

and your constructor to:

constructor() {
    super()
    this.state = { 
      title: localStorage["title"],
      goal: '',
      tech: '',
      features: '',
     details: ''
       }

    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

This is not very elegant but will work. Alternatively you can save to localStorage on unmount.

Upvotes: 1

AugustusOtu
AugustusOtu

Reputation: 27

Yes, you would have to manage this with a state management lib. Localstorage is too extreme. Plus the state management will come handy for other stuff in your app as it grows so i suggest you start right. You can look at mobx or redux.

Upvotes: 0

Related Questions