简体   繁体   中英

Using local storage to retain state of radio buttons when navigating to a new page

The code below represents two sets of radio buttons. Whenever users click one button in each set, they'll be transported to a new page with the exact same set of radio buttons on that new page. But whenever they navigate to a new page or refresh the page, the latest state of radio buttons is lost. Is there a method which we can store the latest value for each set of radio buttons and retrieve/display the latest values whenever we navigate to a new page or when the page is refreshed?

Thanks in advance!

import { useNavigate } from 'react-router-dom';

export default function DisplayHomeOptions() {
    let navigate = useNavigate();
    const [formData, setFormData] = React.useState({ location: "", selector: "" })

    function handleChange(event) {
        const { name, value, type, checked } = event.target
        setFormData(prevFormData => {
            return {
                ...prevFormData,
                [name]: type === "checkbox" ? checked : value
            }
        })
    }

    useEffect(() => {
        const { location, selector } = formData;
        if (location && selector) {
            const target = navTarget[location][selector];
            if (target) {
                navigate(target);
            }
        }
    }, [formData]);

    const navTarget = {

        National: {
            Messages: "/national/messages",
            Polls: "/national/polls",
            Questions: "/national/questions",
        },
        Global: {
            Messages: "/global/messages",
            Polls: "/global/polls",
            Questions: "/global/questions",
        }
    }

    return (
        <div>
            <fieldset>
                <legend>Option #1</legend>
                <input
                    type="radio"
                    name="location"
                    value="Global"
                    onChange={handleChange}
                />

                <label htmlFor="Global">Global</label>
                <input
                    type="radio"
                    name="location"
                    value="National"
                    onChange={handleChange}
                />
                <label htmlFor="National">National</label>
            </fieldset>

            <fieldset>
                <legend>Option #2</legend>
                <input
                    type="radio"
                    name="selector"
                    value="Messages"
                    onChange={handleChange}
                />
                <label htmlFor="Messages">Messages</label>
                <input
                    type="radio"
                    name="selector"
                    value="Questions"
                    onChange={handleChange}
                />
                <label htmlFor="Questions">Questions</label>
                <input
                    type="radio"
                    name="selector"
                    value="Polls"
                    onChange={handleChange}
                />
                <label htmlFor="Polls">Polls</label>
            </fieldset>
        </div>
    )
}```

I would suggest saving the state of all the buttons in one object and then using JSON.stringify() to put that into a string.

I'll add a very short example to illustrate what I mean:

State part of component:

// Default state if browserstorage is empty
const defaultState = {
    button1: false,
    button2: false,
    button3: false,
}
// Get state from browser storage
const currentState = JSON.parse(localStorage.getItem("buttonState"))

// Initialise state with browser state or default state
const [state, setState] = useState(currentState || defaultState)

HandleChange function

const handleChange = (e) => {
    // Create new state
    const newState = {...state, e.target.name: e.target.value}
    // Stringify new state and store it in the browsers local storage
    localStorage.setItem("buttonState", JSON.stringify(newState))
    // Set New State
    setState(newState)
}

The buttons/switches will need to have the name prop set to match the state name for this example to work.

This is a general example but you get the idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM