Last active
May 25, 2020 20:26
-
-
Save stephane777/8caeff84ef4a4a55c7c6d3d1f389074c 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
| ## Definition | |
| ### The Store | |
| The store contains the store and 3 methods which will make the change predictable | |
| as much as possible. | |
| function createStore (reducer) { | |
| <!--// The store should have four parts--> | |
| <!--// 1. The state--> | |
| <!--// 2. Get the state. (getState)--> | |
| <!--// 3. Listen to changes on the state. (subscribe)--> | |
| <!--// 4. Update the state (dispatch)--> | |
| let state | |
| let listeners = [] | |
| const getState = () => state | |
| const subscribe = (listener) => { | |
| listeners.push(listener) | |
| return () => { | |
| listeners = listeners.filter((l) => l !== listener) | |
| } | |
| } | |
| const dispatch = (action) => { | |
| state = reducer(state, action) | |
| listeners.forEach((listener) => listener()) | |
| } | |
| return { | |
| getState, | |
| subscribe, | |
| dispatch, | |
| } | |
| } | |
| ### Create the store | |
| const store = Redux.createStore(reducers, middleware) | |
| There are 3 part when creating the store we need to consider : | |
| 1. Getting the state | |
| 2. Updating the state | |
| 3. Listen for changes. | |
| ### Combine reducers | |
| const reducers = Redux.combineReducers(todos, goals) | |
| ### Middleware | |
| const middleware = Redux.applyMiddleware(checker, logger ) | |
| ### Async with thunk | |
| const thunk = (store) => (next) => (action)=>{ | |
| if ( typeof action === 'function'){ | |
| action(store.dispatch) | |
| } | |
| else next(action) | |
| } | |
| function handleDeleteTodo (todo) { | |
| return (dispatch) => { | |
| dispatch(removeTodoAction(todo.id)) | |
| return API.deleteTodo(todo.id) | |
| .catch(() => { | |
| dispatch(addTodoAction(todo)) | |
| alert('An error occurred. Try again.') | |
| }) | |
| } | |
| } | |
| ### Redux Thunk | |
| import ReduxThunk from 'redux-thunk'; | |
| const middleware = Redux.applyMiddleware(ReduxThunk.default, checker, logger ) | |
| ### Redux connect | |
| const ConnectedApp = connect( state =>({ | |
| loading: state.loading | |
| }))(App) | |
| Connect: Render any component, passing that component any data it needs, | |
| from the store. This connected component will automatically re-render if its data change. | |
| There is no need to manually subscribe to the store. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment