Last active
March 30, 2019 18:02
-
-
Save marvinjude/70a1f0d320ecb9a18af7626b58ad9876 to your computer and use it in GitHub Desktop.
Reducer & Component
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
| function bioReducer(state, action) { | |
| switch (action.type) { | |
| case "SET_NAME": | |
| return Object.assign({}, state, { name: action.payload.name }); | |
| case "SET_AGE": | |
| return Object.assign({}, state, { age: action.payload.age }); | |
| default: | |
| throw new Error( | |
| "Your Action Must Have A Type! Consider calling dispatch with an Action" | |
| ); | |
| } | |
| } | |
| function Bio() { | |
| let [state, dispatch] = useReducer( | |
| /**Reducer */ bioReducer, | |
| /** Initial state*/ { | |
| name: "Mary Slessor", | |
| age: 10 | |
| } | |
| ); | |
| const setName = name => { | |
| dispatch({ type: "SET_NAME", payload: { name } }); | |
| }; | |
| const setAge = age => { | |
| dispatch({ type: "SET_AGE", payload: { age } }); | |
| }; | |
| return ( | |
| <div> | |
| <h1>{state.name}</h1> | |
| <h1>{state.age}</h1> | |
| <button onClick={() => setName("Bro Ade")}>Change Name to Jude</button> | |
| <button onClick={() => setAge(40)}>Change age to 40</button> | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment