I have tried to simplify the code down to what is relevant.
class AnnotatedLayout extends React.Component {
state = {
user: '',
enabled: false,
};
render() {
const { user, enabled } = this.state;
const contentStatus = enabled ? 'Disable' : 'Enable';
const textStatus = enabled ? 'enabled' : 'disabled';
return (
...
<Form onSubmit={this.handleSubmit}>
<FormLayout>
<TextField
value={user}
onChange={this.handleChange('user')}
label="Shop Name"
type="user"
helpText={
<span>
Log in with your store username.
</span>
}
/>
<Stack distribution="trailing">
<Button primary submit>
Submit
</Button>
</Stack>
</FormLayout>
</Form>
...
);
}
handleSubmit = () => {
this.setState({
user: this.state.user
});
localStorage.setItem('user', JSON.stringify(this.state.user));
console.log('submission', this.state);
console.log(this.state.user);
};
handleChange = field => {
return value => this.setState({ [field]: value });
};
}
export default AnnotatedLayout;
Essentially, I have a form component to my webpage that, on submitting, is executing this.handleSubmit, and that function is at the bottom.
What my code SHOULD be doing is saving that submitted string to the localStorage with the key ‘user’, but evidently (you can see below console.log output) that’s not happening.
Any idea what’s going on?
My website is hosted locally, tunneled to a URL, and used as the base URL for a shopify embedded app, just to give all relevant context.
UPDATE
handleSubmit = () => {
this.setState({
user: this.state.user
},
() => localStorage.setItem('user', "SMH"),
console.log(localStorage.getItem('user'))
);
console.log('submission', this.state);
};
Check this out, after submitting my text form now this is what I get
is localStorage like local or something, to the point where it doesnt save anything outside of a function??
2
Answers
It seems like you
handleChange
returns a method, which you need to call again to set the user value.Instead of
Try
The
value
inhandleChange
should accepte
event value, which is the user value to set.