Skip to content

Instantly share code, notes, and snippets.

@Georgegriff
Created January 10, 2022 10:39
Show Gist options
  • Save Georgegriff/88f86f6d9a2577ccb77977f07adfbeac to your computer and use it in GitHub Desktop.
Save Georgegriff/88f86f6d9a2577ccb77977f07adfbeac to your computer and use it in GitHub Desktop.
hooks mutations - todoProvider with initial set of drafts
export const TodoProvider = ({ children }) => {
// New line here!
const [draftTodos, setTodoList] = useState();
const [apiResponse, setApiResponse] = useState(undefined);
useEffect(() => {
const fetchTodos = async () => {
const res = await fetch("./todos.json");
const response = await res.json();
setApiResponse(response);
};
fetchTodos();
}, []);
const existingTodos = useCallback(() => {
const todoMap = new Map();
apiResponse?.todos.forEach((todo) => {
todoMap.set(todo.id, todo);
});
return todoMap;
}, [apiResponse]);
// Other new line!
useEffect(() => {
// pass in initial items from server
if (!draftTodos && existingTodos().size) {
// this () is strange because useCallback was used
setTodoList(existingTodos());
}
}, [existingTodos]);
return return (
<TodoContext.Provider value={{
todoItems: draftTodos ? Array.from(draftTodos.values()) : [],
}}>
{children}
</TodoContext.Provider>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment