Home > Software design >  Persisting state change with localStorage for each input
Persisting state change with localStorage for each input

Time:01-04

So I have two radio button images, one checked and one not. I am trying to persist the change of state to view the corresponding image on button click for each of the inputs. Please help. Here's my code:

import React, { useState, useEffect } from 'react';

const Option = (props) => {
const img1 = <img alt='' src='/radio-active.png' className='radio__img' />;
const img2 = <img alt='' src='/radio-inactive.png' className='radio__img' />;
const [state, setState] = useState(false);

const handleStateChange = () => {
    state === true ? setState(false) : setState(true);
};

useEffect(() => {
    setState(JSON.parse(window.localStorage.getItem('state')));
}, []);
useEffect(() => {
    window.localStorage.setItem('state', state);
}, [state]);

return (
    <div className='option'>
        <div className='radio'>
            <button className='radio__button' onClick={handleStateChange}>
               {state ? img1 : img2}
            </button>

            <p className='option__text radio__text'>{props.optionText}</p>
        </div>
        <button
            className='button button--link'
            onClick={(e) => {
                props.handleDeleteOption(props.optionText);
            }}
        >
            remove
        </button>
    </div>
);
};

export default Option;

CodePudding user response:

All of your Option components are saving the state using the same key ("state"). You'll want each Option to have its own saved state. For each Option, add a new "optionName" property that is the key you want to use when saving the option's value to local storage.

// Change these:
window.localStorage.setItem('state', state);
setState(JSON.parse(window.localStorage.getItem('state')));

// To these:
window.localStorage.setItem(props.optionName, state);
setState(JSON.parse(window.localStorage.getItem(props.optionName)));
  •  Tags:  
  • Related