0

I am creating a component in React which includes a checkbox. I want it to toggle back and forth (on and off) and save the state in local storage so if I go to another page, the toggle will be set to what it was before.

Note: I am not using React 16 and can not use state hooks

I created my component and added the ComponentDidMount and ComponentDidUpdate functions as below.

import * as React from "react";
import { Checkbox } from 'semantic-ui-react'

type Props = {
    label : string
}

type State = {
    status: boolean
}



class ChangeOrder extends React.Component<Props, State> {
    constructor(props) {
        super(props);
        this.state = {
            status: false
        }
    }

    componentDidMount() {
        localStorage.getItem('status') && this.setState({
            status: JSON.parse(localStorage.getItem('status'))
        })
    }

    

    componentDidUpdate(nextProps, nextState) {
        localStorage.setItem('status', JSON.stringify(nextState.status));
    }
    render() {
        return (
            
            <Checkbox
                
                onClick={() => this.setState({ status: !status })}
                label={this.props.label}        
                toggle

            />
        );
    }
}

export default ChangeOrder;

The checkbox works but it does not save the state.

When I right click to inspect and go to Application and navigate to LocalStorage, I see the value of the toggle switch go from false to true but clicking it again does not return it to false.

I want to be able to save and persist the toggle button state between true and false.

2 Answers 2

2

You just need to set the status on click event from the state to be this.state.status, pass the status value to checked prop to ensure the input has the expected value. Also, I prefer not to use stringify the boolean values instead, evaluate the string boolean value to boolean type. I built an app to check out on codesandbox.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks this made it go from false to true and then back to false in the local storage but how do I make it persist that state if I were to refresh the page?
OK, I updated the codesandbox and it's working now according to your reply. Please check the component there.
0

i think your missing this.status in your Checkbox click function change

onClick={() => this.setState({ status: !status })} 

to

onClick={() => this.setState({ status: !this.state.status })}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.