Created
January 10, 2022 10:39
-
-
Save Georgegriff/88f86f6d9a2577ccb77977f07adfbeac to your computer and use it in GitHub Desktop.
hooks mutations - todoProvider with initial set of drafts
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
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