Reputation: 170
I am trying to make a scavenger hunt game with react and I would want the users to be able to save their inputs in local storage. However, when I tried implementing local storage inside my react app, my map function started giving me errors. Any help is appreciated.
class QuestionList extends React.Component{
constructor(props){
super(props)
this.state = {
answers:this.props.answers
}
}
componentDidMount(){
const pastAnswers = localStorage.getItem(`answers${this.props.url}`) ? localStorage.getItem(`answers${this.props.url}`) : this.props.answers
this.setState({answers: pastAnswers})
}
//answer should be a single letter
handleAnswer (answer, num){
let items=[...this.state.answers]
items[num-1]=answer
this.setState({answers:items})
localStorage.setItem(`answers${this.props.url}`, items)
}
renderList = this.props.questions.map((question, index)=>{
return <QuestionCard
question={question}
apiLink={this.props.url}
bar_color_open={this.props.bar_color_open}
bar_color_closed={this.props.bar_color_closed}
onHandleAnswer={this.handleAnswer.bind(this)}
key={index+1}
number={index+1}
/>
})
render(){
const answerList = this.state.answers.map((answer, index)=>{
return <AnswerBox letter={answer} key={index}/>
})
return(
<div className='list-container'>
<div className="grid-container_questions">
<div className={this.props.grid_container}>
{answerList}
</div>
<div className='questionlist-container'>
{this.renderList}
</div>
</div>
</div>
)
}
}
If further code needs to be shown, just tell me and I will place the QuestionCards component up. I don't think, however, that it is needed as that component seems to be working fine.
edit: I have actually tried stringifying before stroing into local storage, but I keep getting this error:
Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.
Upvotes: 0
Views: 395
Reputation: 170
As stated in the comments, this was actually not a local storage problem. I looked into the docs that was linked to me: reactjs.org/docs/cross-origin-errors.html. After adding crossorigin to the div with the id of root, everything started working again.
Upvotes: 0
Reputation: 341
When storing an object in localstorage you first need to JSON.stringify it then when extracting you need to use JSON.parse
Upvotes: 1