Preserve the checkbox state upon refreshing the page

I am facing an issue with keeping the checkbox state saved after a page reload. Currently, I have stored my unchecked checkboxes in localStorage, but I am unsure about what steps to take next. In simple terms, I want the checkbox to remain unchecked when I revisit the page. Below is a snippet of the code:

export default () => {
  const [isDefaultChecked, setDefaultChecked] = useState(true);
  const [isChecked, setChecked] = useState();
  const [isColumn, setColumn] = useState(true);
  const [hiddenColumns, setHiddenColumns] = useState([]);
  const [Checked, setIsChecked] = useState([]);
  
  const onCheckboxChange = (key: string, value: boolean) => {
    console.log(key, value);

    if (!value)
      setHiddenColumns((hiddenColumns) => [...hiddenColumns, { label: key }]);
    else setHiddenColumns(hiddenColumns.filter((x) => x.label !== key));
  };
 return(
 <Dialog
          isOpen={isDialogOpen}
          onOkClick={() => {
            localStorage.setItem(
              "hiddenColumns",
              JSON.stringify(hiddenColumns)
            );
            console.log(hiddenColumns);
            setDialogOpen(false);
          }}
          onCloseClick={() => setDialogOpen(false)}
        >
          <div>
            <Checkbox
              defaultChecked={isDefaultChecked}
              label="Delivery Methods"
              onChange={(value) => onCheckboxChange("deliveryMethods", value)}
            />
          </div>
 )

Thank you for your help!

Answer №1

One suggestion is to consider storing that information in session storage, especially if you don't need it to persist when opening a new tab or window.

To achieve this, simply retrieve the value from session storage when the component is being built. Here's an example of how you can do this:

() => {
  const [isChecked, setChecked] = useState(sessionStorage.getItem('isChecked') || false);
  const onCheckboxChange = (key: string, value: boolean) => {
    sessionStorage.setItem('isChecked', value)
    setChecked(value)
  };

  return (
   ...
   <Checkbox
     value={isChecked}
     label="Delivery Methods"
     onChange={(value) => onCheckboxChange("deliveryMethods", value)}
    />
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to customize Material UI effects when using Chart Js?

Currently, I am working on creating a card component that includes a chart. The line chart was generated using Chart Js and React JS with MUI components. When I enclose the chart within a Paper or Card component, it alters some styles, such as changing t ...

I'm having trouble getting nginx to serve my react index.html as a fallback. Can anyone help troub

I am encountering an issue with my setup involving two docker images on the same machine. One image is running nginx serving a react app, while the other is a back-end express server. The problem arises when my front-end app uses react router to create rou ...

Angular 2 component downgrade issue: What causes the error when constructor parameters are involved? (SystemJS) Unable to resolve all parameters for (?)

Consider this line as an example: constructor(private elementRef: ElementRef, private zone: NgZone) {} In order for the downgrade to be successful without any errors, I must remove the parameters from the constructor. Otherwise, I encounter the follo ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...

Redux sub-application in React

Is it possible to incorporate a sub application within my backbone application using react redux? The purpose would be to have a small number of pages, mainly to test out the concept. ...

Making an Axios request upon clicking a button

Why is the functionality of deleting a quiz from the database not working as expected in the code snippet below, even though it works fine with Postman? deleteQuiz = () => { const quiz = this.state.quizData._id axios.delete(`http://localhost: ...

Tips on resolving the Warning message: "The event handler property `onExited` is a known property in StatusSnackbar component, but it will

When using the StatusSnackbar component, I encountered a warning about a known event handler property onExited. How can I resolve this issue? Component: import Snackbar from '@material-ui/core/Snackbar' import { withStyles } from '@material ...

The validation of DOM nesting has detected that a <td> element cannot be placed within an <a> element

When working on a React project with Material UI, I encountered an issue while trying to create a table. My goal was to make the entire row clickable, directing users to a page with additional information on the subject. Below is the snippet of code for th ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...

calculate the difference between two dates and then add this difference to a new date

Utilizing TypeScript for date calculations. Example: Initial Date 1: "10/06/2021 10:10:05" Initial Date 2: "08/06/2021 11:10:05" Calculate the difference between the two dates, including date/month/year/hour/min/sec/milliseconds. Ensure compatibility wi ...

Enhancing the security of various components by utilizing secure HTTP-only cookies

Throughout my previous projects involving authentication, I have frequently utilized localstorage or sessionstorage to store the JWT. When attempting to switch to httpOnly secure cookies, I encountered a challenge in separating the header component from th ...

Ways to include spacing between label and control within FormControlLabel

I am attempting to create an inline form layout, where the label is positioned next to the form control which goes against the standard practice of most form components. Currently, I have found a solution that works: <Grid container spacing={0}> ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

What specific authentication process does react-aad-msal employ?

I'm curious about the authentication method employed by the react-aad-msal library. Do you know if it utilizes implicit flow? Link to react-aad-msal ...

I am facing the issue of being unable to bind to 'routerlink' because it is not recognized as a known property of 'a', even after I have declared RouterModule in my app.module

Encountering a template parse error when using [routerlink] in an HTML page, despite importing RouterModule. Here's the relevant HTML snippet: <mat-toolbar color="primary"> <h3 [style.color]="white">ADMIN PORTAL</h3> <span cl ...

Tips for effectively typing a collection of React wrappers in TypeScript

I encountered a situation in my team's application where we need the ability to dynamically compose component wrappers (HOCs) without prior knowledge of all the wrapper interfaces. This is mostly needed for swapping out context providers when renderin ...

Error in Angular 2: Component unable to locate imported module

I'm facing an issue where a module I want to use in my application cannot be found. The error message I receive is: GET http://product-admin.dev/node_modules/angular2-toaster/ 404 (Not Found) The module was installed via NPM and its Github reposito ...

I am looking for a way to showcase buffer data as an image in a React application

Need help with displaying images in a react application? function App() { const [imageData, setImageData] = useState(); useEffect(() => { const fetchData = async () => { const response = await axios.get('http://localhost:8000' ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...