Last active
April 10, 2021 10:12
-
-
Save TerryFunggg/6e353f8c6692344aab86daa425ff2302 to your computer and use it in GitHub Desktop.
simple example of how redux works
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 {createStore} from 'redux'; | |
// STORE -> GLOBALIZED STATE | |
// ACTION | |
// like restaurant menu | |
const increment = () => { | |
return { | |
type: 'INCREMENT' | |
} | |
} | |
const decrement = () => { | |
return { | |
type: 'DECREMENT' | |
} | |
} | |
// REDUCER (how your action transfrom to other action) | |
// Like the kitchen in the restaurant, base on the order to cook food for customer | |
const counter = (state = 0, action) => { | |
switch(action.type){ | |
case 'INCREMENT': | |
return state + 1; | |
case 'DECREMENT': | |
return state - 1; | |
} | |
} | |
let store = createStore(counter); | |
// print data to browser console | |
store.subscribe(() => console.log(store.getState())); | |
// DISPATCH (execute the action) | |
// like you order some food from the menu | |
store.dispatch(increment()); // => 1 | |
store.dispatch(decrement()); // => 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment