Created
March 7, 2020 13:07
-
-
Save Mazuh/3407609aa78ac501307d4987fbe37dc8 to your computer and use it in GitHub Desktop.
CRUD for tasks on local storage.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { v4 as uuidv4 } from 'uuid'; | |
const TASKS_KEY = 'tasks'; | |
export const retrieveTasks = () => { | |
const serialized = localStorage.getItem(TASKS_KEY); | |
const tasks = serialized ? JSON.parse(serialized) : []; | |
return tasks; | |
}; | |
export const persistTasks = (tasks) => { | |
localStorage.setItem(TASKS_KEY, JSON.stringify(tasks)); | |
} | |
export default { | |
create: async (taskData = {}) => { | |
if (!taskData.description || !taskData.description.trim()) { | |
throw new Error('Description is required.'); | |
} | |
const existingTasks = retrieveTasks(); | |
const creatingTask = { | |
uuid: uuidv4(), | |
...taskData, | |
}; | |
persistTasks([...existingTasks, creatingTask]); | |
return creatingTask; | |
}, | |
read: async () => { | |
return retrieveTasks(); | |
}, | |
update: async (uuid, taskData = {}) => { | |
const existingTasks = retrieveTasks(); | |
const updatingTask = { ...taskData, uuid }; | |
persistTasks(existingTasks.map(task => task.uuid === uuid | |
? updatingTask | |
: task | |
)); | |
return updatingTask; | |
}, | |
delete: async (uuid) => { | |
const existingTasks = retrieveTasks(); | |
persistTasks(existingTasks.filter(task => task.uuid !== uuid)); | |
return { uuid }; | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment