I'm trying to make a list of star wars movies I have watched. I want to have the capability to check and uncheck what I clicked and have it saved by localStorage. For some reason, sometimes, if I cross more than one movie at a time, after I refresh the page, only the last one i crossed remains crossed. I tried to debug with my console, and I see that the fault is with my state. Sometimes, after I click more than one element, some of them will stay false, instead of turning true.
this is my code:
import React from 'react';
export default class Movie extends React.Component{
constructor(props){
super()
this.state = (localStorage.appState) ? JSON.parse(localStorage.appState)
: { 0: false, 1: false, 2: false, 3: false, 4: false, 5: false};
}
clickedTitle = (event) => {
if (event.target.tagName === "SPAN") {
this.setState({
[event.target.id]: !this.state[event.target.id]
}, () => {
localStorage.setItem('appState',JSON.stringify(this.state))
});
// localStorage.clear()
}
}
render(){
return(
<div className="sw_title" onClick={this.clickedTitle}>
<span id={this.props.index} className={`${this.state[this.props.index] ? "clicked" : "not-clicked"}`}> {this.props.title} </span>
</div>
);
}
}
Thanks in advance for your precious time! April