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