Last active
August 23, 2023 12:39
-
-
Save EmmanuelObua/84095762d613f92fe101ee6109f774c5 to your computer and use it in GitHub Desktop.
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 React, {createContext, useContext, useReducer} from 'react' | |
const TaskContext = createContext(); | |
// a reducer for tasks with the crud operations for the tasks | |
function taskReducer(state,action) { | |
switch(action.type) { | |
case 'ADD_TASK': | |
return [...state, action.payload]; | |
case 'UPDATE_TASK': | |
return state.map(task => task.id === action.payload.id ? { ...task, ...action.payload } : task); | |
case 'DELETE_TASK': | |
return state.filter(task => task.id !== action.payload); | |
default: | |
return state; | |
} | |
} | |
// This is a feature that allows data to be passed through the component tree without having | |
// to pass props down manually at every level. | |
export function TaskProvider({ children }) { | |
// Here we are passing the reducer and an empty array to store the lists of tasks to the useReducer hook. | |
const [tasks, dispatch] = useReducer(taskReducer, []); | |
return ( | |
<TaskContext.Provider value={{ tasks, dispatch }}> | |
{children} | |
</TaskContext.Provider> | |
); | |
} | |
/*TaskConsumer is a component that uses the Context API's Consumer pattern to | |
*access the value provided by the TaskContext context | |
* | |
*The Consumer pattern is one of the ways to consume values from a context. | |
*It allows components to access the context value without needing to be nested within the context provider. | |
*/ | |
export function TaskConsumer({ children }) { | |
const taskContext = useContext(TaskContext); | |
return children(taskContext); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment