Setting Form.Check default value from localStorage

Viewed 143

If have a bunch of checkboxes from React-Bootstrap that I use to toggle columns from a React-Table component, everything works fine but I would like to test store the values from the checkboxes in localStorage so my selection persist when I come back to my site, here is what I have so far

{allColumns.slice(2).map((column) => {
  const locValue = localStorage.getItem(column.id);
  return (
    <div key={column.id} className="table-checkbox-item">
      <Form.Check
        id={column.id}
        onClick={() => storeColumnToggleSelection(column)}
        type="checkbox"
        label={
          column.Header.charAt(0).toUpperCase() +
          column.Header.slice(1)
        }
        className="form-label"
        checked={locValue === null ? true : locValue}
      {...column.getToggleHiddenProps()}
    />
  </div>
  );
})}

And this is how I store the values in localStorage from the onClick method

const storeColumnToggleSelection = (column) => {
  localStorage.setItem(column.id, !column.isVisible);
};

I can see the values update in localStorage, and if I console.log I get the values from it as well, but I have not been able to update the Form.Check using the localStorage values.

UPDATE

I figure out the issue with the checked property, when I get the item from local storage it comes as s string so by apply this

const locValue = JSON.parse(localStorage.getItem(column.id));

The checkboxes do turn on and off, but I noticed the React-Table provides a checked and onChange methods by column.getToggleHiddenProps() so there is a conflict there I should implement my own or could I use what is provided by the props? if so how?

0 Answers
Related