Working on a simple project using react js. What I'm trying to do is to save the "item"(which has an input field for the user to put it) in the localStorage, for the purpose when a user reloads or navigate to other components the item won't be gone, but it will be there.
AddItem.js:
export default class AddItem extends React.Component {
userItems;
constructor(props) {
super(props);
this.state = {
content: "",
items: [],
};
}
update(event) {
this.setState({
message: event.target.value,
});
}
componentDidMount() {
this.userItems = JSON.parse(localStorage.getItem('items'));
if (localStorage.getItem('items')){
this.setState({
items: this.userItems.items,
message: this.userItems.message
})
}else {
this.setState({
items: [],
message: ""
})
}
}
componentWillUpdate(nextProps, nextState){
localStorage.setItem('item', JSON.stringify(nextState));
}
handleClick() {
var items = this.state.items;
items.push(this.state.message);
this.setState({
items: items,
content: "",
});
}
handleChanged(j, event) {
let items = this.state.items;
items[j] = event.target.value;
this.setState({
items: items,
});
}
The problem is that when I type an item in the input field, and I reload the page, the component is not shown at all.
In the application, at the local storage, the value is shown at the google inspect:
But as soon as I navigate to another component or I reload that page, the storage becomes empty like it was in the first time. How can I make it work, so the value doesn't go away when I navigate to another page?
Remove the logic inside componentWillUpdate
and move it to handleItemChanged
. Like so:
export default class AddItem extends React.Component {
userItems;
constructor(props) {
super(props);
this.state = {
content: "",
items: [],
};
}
updateMessage(event) {
this.setState({
message: event.target.value,
});
}
handleClick() {
var items = this.state.items;
items.push(this.state.message);
this.setState({
items: items,
content: "",
});
}
handleItemChanged(i, event) {
var items = this.state.items;
items[i] = event.target.value;
this.setState({
items: items,
});
localStorage.setItem('items', JSON.stringify({items, message :""}));
}
componentDidMount() {
this.userItems = JSON.parse(localStorage.getItem('items'));
if (localStorage.getItem('items')){
this.setState({
items: this.userItems.items,
message: this.userItems.message
})
}else {
this.setState({
items: [],
message: ""
})
}
}
renderRows() {
var context = this;
return this.state.items.map(function (o, i) {
return (
<tr key={"item-" + i}>
<td className="2">
<div>
<input
type="text"
value={o}
onChange={context.handleItemChanged.bind(context, i)}
</tr>