Is there a way to maintain the checked status of the checkboxes after a page refresh?

Is there a way to keep the checkboxes checked even after the page is refreshed in this code snippet? Any code sample or explanation on how to achieve this would be highly appreciated. The complete project code can be found here: https://github.com/Orelso/Project-notes

If you require any other part of the code, please let me know.

import React from "react";
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
CardContent from '@mui/material/CardContent';
{ FormControlLabel, FormGroup, IconButton, Typography } from "@mui/material";
{ DeleteOutlined } from "@mui/icons-material";
{ makeStyles } from "@mui/styles";
Checkbox from '@mui/material/Checkbox';
{ createTheme, ThemeProvider } from "@mui/material";
{ blue } from "@mui/material/colors";


const theme = createTheme ({
    palette: {
        category: {
            color: blue
        }
    }
})

const useStyles = makeStyles({
    test: {
        border: (note) => {
            if (note.category == 'HTML/CSS') {
                return '2px solid blue' 
            } else if (note.category == 'Javascript') {
                return '2px solid green'
            } else if (note.category == "Javascript/React") {
                return '2px solid yellow'
            }else if (note.category == 'MUI') {
                return '2px solid red'
            }
        }
    },
})



export default function NoteCard({ note, handleDelete }) {
    const classes = useStyles(note)

    
    return (
        <div>
            <Card elevation={10} className={classes.test}>
                <CardHeader 
                    action={ // 200
                        <IconButton onClick={() => handleDelete(note.id)}> 
                            <DeleteOutlined />
                        </IconButton>
                    }
                    title={<span style={{fontFamily: "monospace", color: "#000000"}}>{note.title}</span>}
                    subheader={<span style={{fontFamily: "Courier New", color: "#000000"}}>{note.category}</span>}                    />
                <CardContent>
                    <FormGroup>
                    <FormControlLabel sx={{color: '#000000'}} control={<Checkbox color="warning"  />} label={note.details} />
                    <FormControlLabel sx={{color: '#555555'}} control={<Checkbox  />} label={note.details2} />
                    <FormControlLabel sx={{color: '#000000'}} control={<Checkbox  />} label={note.details3} />
                    <FormControlLabel sx={{color: '#555555'}} control={<Checkbox  />} label={note.details4} />

                    </FormGroup>
                </CardContent>
            </Card>
        </div>
    )
}

Answer №1

Utilizing redux persist allows you to securely store your data in local storage, providing a convenient method for retrieving the data from a backend via REST API.

Answer №2

If you want to preserve user input data, consider utilizing the capabilities of local storage.

localStorage.setItem("keyname", "valueName");

To retrieve the stored data in a specific component, simply access the local storage.

localStorage.getItem("keyname");

In your scenario, set an item in Local Storage when the user makes changes and update the state accordingly. Apply useEffect to fetch the item from local storage each time the component is rendered.

var style, classes;
const [mystate,setMystate] = useState();

useEffect(()=>{
    style = localStorage.getItem(keyname);
    classes = setMystate(style);
},[]);

You can then utilize this variable as needed, ensuring to update the state whenever there are relevant user modifications.

If you require persistent checkbox data across the application, rather than just within one component, consider implementing context or redux. Normally, we create a global context for accessing shared variables like application styles or user login status.

Trust this guidance proves beneficial! Best regards,

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

"Error: The function $(...).autocomplete is not recognized" in conjunction with Oracle Apex

Currently experiencing some frustration trying to solve the issue at hand. The Uncaught TypeError: $(...).autocomplete is not a function error keeps popping up and I have exhausted all resources on Stack Overflow in an attempt to fix it. This problem is oc ...

Encountering a 404 error while using Node.js for app.get requests with Postgres as the

Currently, I am in the process of learning Node.js by following a tutorial that guides me on building a simple API. The tutorial utilizes a sample database for demonstration purposes, but I decided to use my own Postgres DB instead. However, when trying to ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

Discover the syntax for reading route parameters in Angular

Currently, I am integrating the Paypal API into my project. After confirming a purchase, Paypal redirects to a specified URL. I set the desired URL as "localhost:4200/shop/order". However, when Paypal returns the URL, it appends the token and payerid at th ...

Most effective method for showcasing the image once it has been successfully loaded

At the moment, I am considering two methods to display an image after it has been loaded. Initial Method <img id="myImage" /> var img = new Image(), x = document.getElementById("myImage"); img.onload = function() { x.src = img.src; }; img ...

Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component: <template> <div> <multiselect v-model="values" :options="options"> ...

Can Python's datetime object be used interchangeably with a JavaScript date object?

Take for instance in python, a date might look like: 2020-06-19T11:32:16.548109Z, is there a method I can utilize to transform this into a javascript Date object? ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

Steps to alter the color of a JSONLoader-generated object with a simple click

Recently, I've been delving into Three.js and managed to create an object using the JSONLoader. The material of the object is currently grey in color. My goal now is to allow users to change the color of the object by clicking on a button that I have ...

Attempting to retrieve data from a JSON file according to the choice made by the user in a dropdown menu

My goal is to create a user interface where users can select options from a drop-down list and receive corresponding output based on their selection. The drop-down list options are populated using data from a JSON file, and the desired output is derived fr ...

loading the css and javascript files based on the specified prop parameter

In the process of working on a ReactJS file that utilizes the react-ace library, I currently have the following code implemented. import React, { Component } from 'react'; import 'brace/mode/html'; import 'brace/theme/monokai&apos ...

When retrieving the card in React, only the first element is affected by the .map function

There seems to be an issue with Arrays.map as it is only working for the first object in the array. Here is the main function: function App(){ return ( <div> <NavBar /> { data.map((prop) =&g ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Error: The function styles$1.makeStyles is not defined

Currently, I am experimenting with rollup for bundling. However, when I run the code, I encounter the following problem: https://i.stack.imgur.com/8xLT3.png import { makeStyles } from '@material-ui/styles'; const styles = makeStyles({ subHead ...

I am interested in deleting an element from Firebase using JavaScript

I'm struggling to grasp the concept of deleting an item from my Firebase database. I have successfully created a function (saveEmployee) to add items, but removing them is where I hit a roadblock. HTML <tbody ng-repeat="employee in employees"> ...

Creating a Vue2 modal within a v-for loop to display a dynamic

Recently, I've been working on implementing a vue2 modal following the instructions provided in the official Vue documentation at https://v2.vuejs.org/v2/examples/modal.html. The code snippet I have been using looks something like this: <tbody v-i ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

Ways to pass JavaScript variables to a Python script

Hey there! I'm currently facing an issue with retrieving variables from JS to use in my python code. Despite trying methods like AJAX and JQuery, I haven't had much success yet. It's possible that I'm missing something crucial in the pr ...