Skip to content

Instantly share code, notes, and snippets.

@Mazuh
Created March 7, 2020 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mazuh/3407609aa78ac501307d4987fbe37dc8 to your computer and use it in GitHub Desktop.
Save Mazuh/3407609aa78ac501307d4987fbe37dc8 to your computer and use it in GitHub Desktop.
CRUD for tasks on local storage.
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