1

I am trying when I click on a checkbox it should get selected and save its value true in localstorage so that if the page is refreshed it should get value from the localstorage, similarly for second checkbox if it is selected too then also save its value true in localstorage.

In simple way if I select a both the checkboxes it should retain even after page refresh this is what I am trying for

Here is my code is what I have tried

Link - https://codesandbox.io/s/musing-architecture-p2nrg?file=/src/App.js:0-1760

import React from "react";
import "./styles.css";
import { Form } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  const data = {
    naming: localStorage.getItem("naming") || false,
    fullname: localStorage.getItem("fullname") || false
  };
  const [currentCheckboxId, setCheckboxId] = React.useState(data);

  const setCheckbox = event => {
    const naming = event.target.checked;
    console.log(naming);
    localStorage.setItem("naming", naming);
    setCheckboxId({
      ...data,
      naming: event.target.checked
    });
  };

  const setCheckbox2 = event => {
    const fullname = event.target.checked;
    console.log(fullname);
    localStorage.setItem("fullname", fullname);
    setCheckboxId({
      ...data,
      fullname: event.target.checked
    });
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Form>
        <>
          <Form.Check
            onChange={setCheckbox}
            type="checkbox"
            label="Check me out"
            id="first"
            checked={currentCheckboxId.naming}
          />
          <Form.Group controlId="email">
            <Form.Label>Email Address</Form.Label>
            <Form.Control type="text" placeholder="Enter email" />
          </Form.Group>
        </>
        <>
          <Form.Check
            onChange={setCheckbox2}
            type="checkbox"
            label="Check me out"
            id="second"
            checked={currentCheckboxId.fullname}
          />
          <Form.Group controlId="fullname">
            <Form.Label>Name</Form.Label>
            <Form.Control type="text" placeholder="Enter name" />
          </Form.Group>
        </>
      </Form>
    </div>
  );
}

1 Answer 1

1

Here is what you need to do:

  1. Initialize the state with false
  2. Use useEffect to run at mounted and retrieve checkbox values from LocalStorage and setState accordingly
  3. Use setState with updater function to set new state which depends on current state
export default function App() {

  // 1. Initially "false"
  const [currentCheckboxId, setCheckboxId] = React.useState({
    naming: false,
    fullname: false
  });

  // 2. useEffect to run @ mounted:
  // get from LS and update the state
  React.useEffect(() => {
    const data = {
      naming: localStorage.getItem('naming') === 'true' ? true : false,
      fullname: localStorage.getItem('fullname') === 'true' ? true : false
    };
    setCheckboxId(data);
  }, []);

  const setCheckbox = event => {
    const naming = event.target.checked;
    console.log('naming', naming);
    localStorage.setItem('naming', naming);

    // 3. use "function" with prevData as first argument to setState
    setCheckboxId(prevData => ({
      ...prevData,
      naming: naming
    }));
  };

  const setCheckbox2 = event => {
    const fullname = event.target.checked;
    console.log('fullname', fullname);
    localStorage.setItem('fullname', fullname);

    // 3. same as above
    setCheckboxId(prevData => ({
      ...prevData,
      fullname: fullname
    }));
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Form>
        <>
          <Form.Check
            onChange={setCheckbox}
            type="checkbox"
            label="Check me out"
            id="first"
            checked={currentCheckboxId.naming}
          />
          {/* Rest of your code */}
}

Here is a playground.

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

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.