Last active
June 21, 2023 08:01
-
-
Save zaguiini/f5d343a7579bac8c530beabf781677c9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 from 'react' | |
const Store = React.createContext() | |
const useStore = () => React.useContext(Store) | |
const reducer = (state, action) => { | |
switch(action.type) { | |
case 'ADD_TODO': | |
return { ...state, todos: [...state.todos, action.payload] } | |
default: | |
return state | |
} | |
} | |
const initialValue = { | |
todos: [], | |
} | |
const App = () => { | |
const [value, dispatch] = React.useReducer(reducer, initialValue) | |
return ( | |
<Store.Provider value={{ ...value, dispatch }}> | |
<TodoList /> | |
</Store.Provider> | |
) | |
} | |
const TodoList = () => { | |
const { todos, dispatch } = useStore() | |
const add = (text) => { | |
dispatch({ | |
action: 'ADD_TODO', | |
payload: text, | |
}) | |
} | |
return ( | |
<div> | |
{todos.map((todo, idx) => <div key={idx}>{todo}</div>)} | |
<AddTodo onAdd={add} /> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment