Created
July 8, 2021 11:05
-
-
Save adambutler/ebfd0df625a3e779826d8a4f4270134c 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
// State | |
const initialState = { | |
counter: 0, | |
user: undefined, | |
token: undefined | |
} | |
// Store | |
store = createStore(initialState) | |
// Provdier | |
function App() { | |
return ( | |
<Provider store={store}> | |
<App /> | |
</Provider> | |
); | |
} | |
// Action type | |
const INCREMENT = 'INCREMENT_COUNTER' | |
const SET_COUNTER = 'SET_COUNTER' | |
const SET_USER = 'SET_USER' | |
const CHANGE_USERNAME = 'CHANGE_USERNAME' | |
// Action | |
const incrementAction = { type: INCREMENT } | |
// const setCounterAction = { type: SET_COUNTER, nextValue: 123 } | |
// const setUser = { type: SET_COUNTER, user: { id: 1, name: "Adam Butler" }, token: "abc123"} | |
// const changeUsername = { type: CHANGE_USERNAME, name: "Tom Cartwright" } | |
// Action Generators | |
const incrementActionGenerator = () => ({ type: INCREMENT }) | |
const setCounterActionGenerator = (nextValue) => ({ type: SET_COUNTER, nextValue }) | |
const setUserGenerator = (user, token) => ({ type: SET_COUNTER, user, token}) | |
const changeUsernameGenerator = (name) => ({ type: CHANGE_USERNAME, name}) | |
// Component | |
const Counter = () => { | |
const dispatch = useDispatch(); | |
const count = useSelector((state) => state.counter) | |
return ( | |
<div> | |
<span>{count}</span> | |
<button onClick={() => dispatch(incrementActionGenerator())}>Increment</button> | |
</div> | |
) | |
} | |
// Reducer | |
const someReducer = (state, action) => { | |
switch (action.type) { | |
case INCREMENT: | |
return { ...state, counter: state.counter + 1 } | |
case SET_COUNTER: | |
return { ...state, counter: action.nextValue } | |
case SET_USER: | |
return { ...state, user: action.user, token: action.token } | |
case CHANGE_USERNAME: | |
return { | |
...state, // <- Spread here | |
user: { | |
...action.user, // <- Spread here too | |
name: action.name | |
} | |
} | |
default: | |
break; | |
} | |
} | |
// Immer Reducer | |
const immerReducer = (state, action) => { | |
produce((draft, action) => { | |
switch (action.type) { | |
case INCREMENT: | |
draft.counter++; | |
case SET_COUNTER: | |
draft.counter = action.nextValue; | |
case SET_USER: | |
draft.user = action.user; | |
draft.token = action.token; | |
case CHANGE_USERNAME: | |
draft.user.name = action.name; | |
} | |
}, state) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment