-1

My inputs lose their values when I refresh the page.

It is a simple small React app that reflects what I’m doing in a larger app, with only one component

I defined a state in the component that holds the value of the inputs (name and email).

There’s a button that toggles the presentation of the form that contains these two inputs.

I’m using local storage to keep the value of the toggle, since I don’t want to lose it when I refresh the page.

The problem is that when I refresh the page, my two inputs lose their values, but the state is keeping it correctly

Here’s the code

import React, { Component } from 'react'

export default class AComponent extends Component {
constructor() {
    super()
    this.state = {
        input:{
            name: '',
            email: ''
        },
        showForm: false
    }
}

componentDidMount() {
    localStorage.setItem("showForm", 'false')
}

componentDidUpdate() {
    this.showElements()
}

handleShowForm= (e) => {
    let storageValue = this.state.showForm
    localStorage.setItem("showForm", storageValue ? 'false' : 'true')
    this.setState({input:{...this.state.input}, showForm: !this.state.showForm})
}

handleFormInputs = (e) => {
    this.setState({input:{...this.state.input, [e.target.name]: e.target.value}, 
        showForm: this.state.showForm})
}

showElements = () => {
    if (localStorage.getItem("showForm") === 'true') {
        return (
            <div>
                <form>
                    <label>name</label>
                    <input 
                        name="name" 
                        type="text" 
                        value={this.state.input.name}
                        onChange={this.handleFormInputs} 
                        required>
                    </input>
                    <label>email</label>
                    <input 
                        name="email" 
                        type="email" 
                        value={this.state.input.email}
                        onChange={this.handleFormInputs} 
                        required>
                    </input>                   
                </form>
            </div>
        )
    }
}

render() {
    return (
        <div>
            <button onClick={() => this.handleShowForm()}>Toggle ShowElements</button>
            {this.showElements()}
        </div>
    )
}

}

What am I missing here, why these two inputs lose their values

Thanks in advance

Rafael

Rafael
  • 2,413
  • 4
  • 32
  • 54

1 Answers1

0

When you refresh the page, it destroys the component, which when the page reloads, it renders the component again with initial state. If you want to keep the state when the page refreshes, you can do the same as you do for the showForm (use the local storage).

Another alternative, is you can look at doing server side rendering (using third party libraries that store the state of your component on the server and push it to your client).

Jason Bellomy
  • 442
  • 2
  • 7