Home > OS >  localStorage.setItem from component to reducer
localStorage.setItem from component to reducer

Time:11-10

Pretty new to react. Im trying to set a value in local state when I submit my form. I´ve done it in the wrong order, so I think that the getItem part in the reducer looks fine, but I dont really know how to setItem. Probably want to do that in the onSubmit function.

survej.js (reducer)


```
const initialState = localStorage.getItem('survey')

? {
  klar: JSON.parse(localStorage.getItem('survey')).klar, 
  fraga1: null,
  fraga2: null,
  fraga3: null,
  fraga4: null    
}
: {
  klar: false,
  fraga1: null,
  fraga2: null,
  fraga3: null,
  fraga4: null  
}

const survey = createSlice({
  name: 'survey',
  initialState,
  reducers: {
    setFraga1: (store, action) => {
      store.fraga1 = action.payload         
    },
    setFraga2: (store, action) => {
      store.fraga2 = action.payload         
    },
    setFraga3: (store, action) => {
      store.fraga3 = action.payload         
    },
    setFraga4: (store, action) => {
      store.fraga4 = action.payload         
    },
    setKlar: (store, action) => {
      store.klar = action.payload  
    }
  }
})

export default survey`
```

```

Form.js
```

```
`import React, { useState, useEffect } from 'react'
import { useDispatch, batch } from 'react-redux'

import survey from '../reducers/survey'

import Summary from './Summary'
import TextWrapper from './TextWrapper'
import NextButton from './NextButton'
import SubmitBtn from './SubmitBtn'

const Form = () => {   
  const [newCounter, setNewCounter] = useState(0)
  const [newFraga1, setNewFraga1] = useState('')
  const [newFraga2, setNewFraga2] = useState('')
  const [newFraga3, setNewFraga3] = useState('')
  const [newFraga4, setNewFraga4] = useState('')

  const dispatch = useDispatch() 
    
  const onCounterIncrease = () => {
    setNewCounter(newCounter   1)
  }

  const onSubmit = () => { 
    batch(() => {
      dispatch(survey.actions.setFraga1(newFraga1))
      dispatch(survey.actions.setFraga2(newFraga2))
      dispatch(survey.actions.setFraga3(newFraga3))
      dispatch(survey.actions.setFraga4(newFraga4))
      dispatch(survey.actions.setKlar(true))

      setNewCounter(newCounter   1)
    })
  }    

  const on1Change = (event) => {
    setNewFraga1(event.target.value)    
  }
  const on2Change = (event) => {
    setNewFraga2(event.target.value)        
  }
  const on3Change = (event) => {
    setNewFraga3(event.target.value)        
  }
  const on4Change = (event) => {
    setNewFraga4(event.target.value)        
  }

  return (
    <div className="wrapper">
      <form className="form" onSubmit={(event) => event.preventDefault()}>
        <div className="form-wrapper">                     
          <div className="questions-wrapper"> 
            {newCounter === 0 && (
              <div>
                <TextWrapper />
                <NextButton onCounterIncrease={onCounterIncrease} />
              </div>
            )}
            {newCounter === 1 && (
              <div> 
                <p>Vem är: </p>
                  <input 
                    tabIndex={1}
                    type="text"
                    className="text-input"
                    value={newFraga1}
                    onChange={on1Change} />
                <NextButton onCounterIncrease={onCounterIncrease} /> 
              </div>
            )}
            {newCounter === 2 && (
              <div> 
                <p>Vem är: </p>
                  <input
                    tabIndex={1}                    
                    type="text"
                    className="text-input"
                    value={newFraga2}
                    onChange={on2Change} />
                <NextButton onCounterIncrease={onCounterIncrease} /> 
              </div>
            )}
            {newCounter === 3 && (
              <div>   
                <p>Vem är: </p>
                  <input 
                    tabIndex={1}
                    type="text"
                    className="text-input"
                    value={newFraga3}
                    onChange={on3Change} />
                <NextButton onCounterIncrease={onCounterIncrease} /> 
              </div>
            )}
            {newCounter === 4 && (
              <div>
                <p>Vem är: </p>
                  <input
                    tabIndex={1}
                    type="text"
                    className="text-input"
                    value={newFraga4}
                    onChange={on4Change} />
                <SubmitBtn onSubmit ={onSubmit} /> 
              </div>
            )}
            {newCounter === 5 && (
              <div>
                <Summary />
              </div>
            )}
          </div>
        </div>
      </form>
    </div>
  )
}
```

When I press the submit button at the last question I want to update localStorage so that klar: is true whenever I refresh the page.

CodePudding user response:

As you have figured out. Yes, you can use localStorage.setItem in the onSubmit function.

like

const onSubmit = () => {
  const survey = localStorage.getItem('survey');
  const newSurvey = {
    ...JSON.parse(survey),
    klar: true,
    // if you want to store this as well.
    fraga1: newFraga1,
    fraga2: newFraga2,
    fraga3: newFraga3,
    fraga4: newFraga4
  };
  
  localStorage.setItem('survey', JSON.stringify(newSurvey));
  // update your state here
}

And bonus tips If you use useState the component will rerender every time you type. so you useRef.

Here is a detailed link from Web Dev Simplified: Form example react mistake.

Hope this helps, comment if there is anything and if still didn't work provide more details or recreate it in codepen online tool. Thanks.

  • Related