Store values from multiple select in react

Viewed 171

I have a variable with the number of select items, this number depends on some API, and I want to store the selection of each question into localstorage so each time the page reloads the selection stays remained, I don't know how to do it.

 { Object.entries(this.state.liste).map( ([ke,values]) => {
                          let question=ke
 return (                            
 <div  name = "question"  >
  <h6 className="left">{ke}</h6>     
  < select className="right"  key={values} name = "answer to each question"  onChange={(event) => 
   this.handleChangeaa(question,event)} >
   <option value={this.state.selected} selected disabled hidden onChange={(value)=> 
    console.log(value)}>  Not answered </option> 

    {Object.values(values).map(key=>{ 
     return (<option  key={key.id} id={key}>{key}</option>) })}
   </select>
   </div>
    ) })}

enter image description here

1 Answers

In localStorage, you can only set a value as a string. You simply have to insert in the localStorage some pairs of key/values for each questions that have a selected option. In this case, the key will be the id of your question and the value the value of your selected option.

In your handleChangeaa callBack, you will have something like this :

handleChangeaa(question, event) {
    // Check before if the localStorage is available
    localStorage.setItem(question.id, event.target.value);
}

Then when your form component will be instantiated, you will simply have to retrieve this information from your localeStorage with the localStorage.getItem function :

componentDidMount() {
   // Check if localStorage is available
   const stateListCpy = {...this.state.liste}
   ["question1", "question2"].forEach((questionId) => {
       const questionValue = localStorage.getItem(questionId);

       if (questionValue) {
           const questionIndex = stateListCpy.findIndex((questionBlock) => questionBlock.ke === questionId )
           if (questionIndex !== -1) {
               stateListCpy[questionIndex].values = questionValue;
           }
       }
   })
   this.setState({
       liste = stateListCpy;
   })
}

And with that you will have your selects initialized with the right values from your localStorage.

Good luck !

Related