skip to Main Content

I’m making a React site similar to todolist. My todolist has navigation and different pages under its theme. Each page has a separate todolist of its own. That is, the page with the theme “General” has all the usual shuffles. The page with the topic “Urgent” has all the relevant tasks. At the moment I could only write a code with local storage that saves the todos, but all these todos are mixed up in different pages. That is, in the “Urgent” page there are tasks from the “General” page. How can I make it so that tasks are saved only in a separate page?

I have several pages as files. I import all of them into App(file). In the App I use BrowserRouter(Router, Routes, Route) and NavLink from react-router-dom

I am using the below code as a component. I use this component on every todolist page

    function NewAchieve() {

    const oldTasks = localStorage.getItem("tasks")
    console.log(oldTasks)

    const [ tasks, setTasks] = useState(JSON.parse(oldTasks) || []);
    const [ newTask, setNewTask] = useState("");

    useEffect(() => {
        localStorage.setItem("tasks", JSON.stringify(tasks, newTask))
    }, [tasks, newTask])



    function handleInputChange(event) {
        setNewTask(event.target.value)
    }
    

    function addTask() {
        setTasks (t => [...t, newTask]);
        setNewTask("")
    }


    return (      
    <>         
        <input className="inputAdd" type="text" placeholder={inputText} value={newTask} onChange={handleInputChange} />   
        <button className="addBtn" onClick={addTask}>{add_btn}</button>
        <div>
            {tasks.map((task, index) => 
                    <div className="btnChip" key={index}>
                        <Chip>{task}</Chip>
                        </div>

            )}
        </div>
    </>    
    )


}

export default NewAchieve

Chip. This is a custom component, The same button only enhanced with css and small features.

NewAchieve. It is also a component that is used on every page in todolist

2

Answers


  1. In order to save such grouped data to local storage, you will need to –

    1. Represent the data as JSON object
    const data = {
      general: [
        { id: '1', title: 'you note title' },
        // and so on for other todos
      ],
      urgent: [
        { id: '2', title: 'you note title' },
        // and so on for other todos
      ],
      someOtherCategory: [],
    }
    
    1. Convert the data to string, and store in localStorage
    Object.keys(data).forEach((todoLabel => {
      // Repeat the following for each todo category (general, urgent, ...)
      localStorage.setItem(todoLabel, JSON.stringify(data[todoLabel]));
    }));
    
    1. Inorder to retrieve data from your local storage
    // This list must be hardcoded based on your labels.
    // You cannot just run Object.keys(localStorage),
    // since your application might have some other data 
    // stored in local storage as well.
    const todoLabels = ['general', 'urgent', 'someOtherCategory'];
    
    const retrievedData = todoLabels.reduce((acc, curr) => {
      return {
        ...acc,
        [curr]: JSON.parse(localStorage.getItem(curr)),
      }
    }, {});
    

    However, you should only use this approach for simple applications.

    As the number of todos in each category increases, parsing the string to JSON will become more expensive.

    Consider using IndexedDB or SQLite Wasm for this. This might prove beneficial for your project once you start adding some complicated features like parent-child relation between todos, due dates and priorities, todo groups/folders, etc.

    Login or Signup to reply.
  2. Where do you have logic to discern which items are on which page? Currently every page reads and writes the same "tasks":

    const oldTasks = localStorage.getItem("tasks");
    

    Logically separate them.

    For example, the "General" page could save its items with the key "tasks-General" and the "Urgent" page could save its items with the key "tasks-Urgent". Such as:

    localStorage.setItem("tasks-General", JSON.stringify(tasks))
    

    Or all items could be saved under "tasks" and the tasks themselves could indicate their status. Such as:

    const oldTasks = JSON.parse(localStorage.getItem("tasks") || "[]")
                         .filter(t => t.type === "General");
    

    In which case the data itself would need to hold that information. In the above example each "task" would have a type property indicating what page it belongs to. You can indicate this however you like.

    Currently if every page saves the array as "tasks" and every page reads all of the "tasks" then every page will have all of the "tasks". You can separate them logically any way you like, but you have to separate them logically somehow.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search