I can't save my added to-do item when refresh the page
When I add the to-do title in the text field, it is added but when I refresh the page it disappears. Also, when I add several items, the last one disappears when refresh the page.
Note: I have used local storage in last line of addTaskButton()
I used usestate hook in the function addTaskButton(). This is supposed to add newToDo to my Array of objects todoItems
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import Box from '@mui/material/Box';
import Container from '@mui/material/Container';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Typography from '@mui/material/Typography';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToDoItem from './ToDoItem';
import { createTheme, ThemeProvider} from '@mui/material/styles';
import TextField from '@mui/material/TextField';
import { useState,useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
let todos=[
{
id:uuidv4(),
title:'First Task',
details:'Reading Book',
isCompelete:false
},{
id:uuidv4(),
title:'Second Task',
details:'Watching TV',
isCompelete:false
},
{
id:uuidv4(),
title:'Third Task',
details:'Doing Workout',
isCompelete:false
}
]
export default function ToDoList() {
const [todoItems,setToDoItems]=useState(todos);
const [textValue,setTextValue]=useState('');
function enterTask(e){
setTextValue(e.target.value);
}
function addTaskButton(){
const newToDo={
id:uuidv4(),
title:textValue,
details:'',
isCompelete:false
}
setToDoItems([...todoItems,newToDo]);
console.log(todoItems);
localStorage.setItem('todos',JSON.stringify(todoItems));
}
useEffect(()=>{
setToDoItems( JSON.parse (localStorage.getItem('todos')));
},[])
const todoMaterials=todoItems.map((t)=>{
return( )
})
function handleCheckClick(todoId){
const updatedTodos=todoItems.map((t)=>{
if (todoId==t.id){
t.isCompelete =!t.isCompelete;
}
return t
}
)
setToDoItems(updatedTodos);
localStorage.setItem('todos',JSON.stringify(updatedTodos));
}
function deleteTask(todoId){
const newAfterDelete=todoItems.filter((t)=>{
if(t.id==todoId){
return false
}else{
return true
}
})
setToDoItems(newAfterDelete);
localStorage.setItem('todos',JSON.stringify(newAfterDelete));
}
const [alignment, setAlignment] = React.useState('web');
const handleChange = (event, newAlignment) => {
setAlignment(newAlignment);
};
const theme = createTheme({
typography: {
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
},
});
const card = (
My Tasks
All
Complete
Incomplete
{todoMaterials}
);
return (
<>
{card}
>
)};