I am trying to save the value of checkboxes in local storage, so when the user reloads the page, they remain checked/unchecked. I have an "isChecked" state and a handleOnChange function.
What im trying to do is store the value on the state, and every time the onChange fuction runs, i set the 'checkbox' key on local storage to the value of the checkbox.
this is what my component looks like
import React from "react";
import { useState, useEffect } from "react";
const Pdf = (props) => {
const [shown, setShown] = useState(false);
const [isChecked, setIsChecked] = useState(localStorage.getItem('checkbox') === 'true');
const handleOnChange = (e) => {
setIsChecked(localStorage.getItem('checkbox'));
localStorage.setItem('checkbox',`${e.target.checked}`)
}
const toggle = () => {
setShown((prevState) => !prevState);
alert(isChecked)
};
return (
<div className="pdfContainer row container justify-content-center">
<section className="justify-content-center">
<h1 className="row justify-content-center h1--style">
Κεφάλαιο {props.id}
</h1>
<p className="row justify-content-center p--style">{props.info}</p>
</section>
<button onClick={toggle} className=" shadow button--style">
Μάθημα {props.id}
</button>
{shown && <embed className=" pdf" src={props.pdf} />}
<div className="pdfChecked input-group-text input-group ">
<input
type="checkbox"
id='pdfchecked'
name="pdfChecked"
value='1'
checked={isChecked}
onChange={handleOnChange}
/> <label className="input--label"> Διάβασα το κεφάλαιο!</label>
</div>
</div>
);
};
export default Pdf;
I understand that this is very buggy, and very much not how you're supposed to do it. I found the local storage concept hard to grasp as a beginner, and i have tried many ways to make this work. As of now, it kinda works, meaning when i reload the page it stays the same, but i have to click on the checkbox multiple times! SO buggy. Any help, especially letting me know why my thought process is wrong, would be appreciated!