Skip to content

Commit 047d85b

Browse files
committed
Redux data flow
1 parent 5a9839f commit 047d85b

File tree

6 files changed

+91
-57
lines changed

6 files changed

+91
-57
lines changed

Redux/Actions.md

+34-29
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
### The Action Creator.
2+
3+
In this file, you will write the functions that dispatch an action. These functions will be linked to your component props by the container’s mapDispatchToProps function. At that point, a component should be able to call a prop like a function and know that it will lead to an action getting dispatched. After the action is dispatched, it will be heard by only one type of function: the reducer.
4+
15
### An action is a plain object describing what happened. For example:
6+
27
[https://redux.js.org/basics/dataflow](https://redux.js.org/basics/dataflow)
38

4-
{ type: 'LIKE_ARTICLE', articleId: 42 }
5-
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
6-
{ type: 'ADD_TODO', text: 'Read the Redux docs.' }
9+
{ type: 'LIKE_ARTICLE', articleId: 42 }
10+
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
11+
{ type: 'ADD_TODO', text: 'Read the Redux docs.' }
712
Think of an action as a very brief snippet of news. “Mary liked article 42.” or “‘Read the Redux docs.' was added to the list of todos.”
813

914
Check my working file -
@@ -13,29 +18,31 @@ Check my working file -
1318

1419
So from my working file this is an example for post actions
1520

16-
- /home/paul/codes-Lap/React/React-snippets/redux-show-list-of-micro-blog-posts/src/actions/postActions.js
21+
- /home/paul/codes-Lap/React/React-snippets/redux-show-list-of-micro-blog-posts/src/actions/postActions.js
1722

1823
```js
19-
import { FETCH_POSTS, NEW_POST } from './types'
24+
import { FETCH_POSTS, NEW_POST } from "./types";
2025

2126
// function with ES5 way to dispatch the data to the reducer
2227
export function fetchPosts() {
23-
return function(dispatch) {
24-
fetch('https://jsonplaceholder.typicode.com/posts')
25-
.then(res => res.json())
26-
.then(posts => dispatch({
27-
type: FETCH_POSTS,
28-
payload: posts
29-
}));
30-
}
28+
return function(dispatch) {
29+
fetch("https://jsonplaceholder.typicode.com/posts")
30+
.then(res => res.json())
31+
.then(posts =>
32+
dispatch({
33+
type: FETCH_POSTS,
34+
payload: posts
35+
})
36+
);
37+
};
3138
}
3239
```
3340

34-
3541
## Object serialization
42+
3643
Object serialization is the process of converting an object’s state to a string from which it can later be restored. ECMAScript 5 provides native functions JSON.stringify() and JSON.parse() to serialize and restore JavaScript objects. These functions use the JSON data interchange format.
37-
By convention, the top-level state in React, is an object or some other key-value collection like a Map, but technically it can be any type. Still, you should do your best to keep the state serializable. Don't put anything inside it that you can't easily turn into JSON.
3844

45+
By convention, the top-level state in React, is an object or some other key-value collection like a Map, but technically it can be any type. Still, you should do your best to keep the state serializable. Don't put anything inside it that you can't easily turn into JSON.
3946

4047
## Another working example of action dispatching to reducer and updating state
4148

@@ -49,17 +56,15 @@ In ..actions/itemActions.js I have the below
4956

5057
```js
5158
export const getItems = () => dispatch => {
52-
53-
dispatch(setItemsLoading()); // because I want the loading to be set to true for now.
54-
55-
axios.get('/api/items')
56-
.then(res => {
57-
dispatch({
58-
type: GET_ITEMS,
59-
payload: res.data
60-
})
61-
})
62-
}
59+
dispatch(setItemsLoading()); // because I want the loading to be set to true for now.
60+
61+
axios.get("/api/items").then(res => {
62+
dispatch({
63+
type: GET_ITEMS,
64+
payload: res.data
65+
});
66+
});
67+
};
6368
```
6469

6570
And in ..reducers/itemReducer.js I have -
@@ -74,8 +79,8 @@ switch(action.type) {
7479
}
7580
```
7681
77-
So, ``getItems()`` function is the action, and when its invoked or run, then it will dispatch this ``action.type``, which is ``GET_ITEMS`` to the reducers. And then in the reducer I will just return the state ( with spread operator ``...state`` ), and bring it into my component.
82+
So, `getItems()` function is the action, and when its invoked or run, then it will dispatch this `action.type`, which is `GET_ITEMS` to the reducers. And then in the reducer I will just return the state ( with spread operator `...state` ), and bring it into my component.
7883
79-
And the way, I invoke this function in my reducer is by doing the ``action.type`` and then applying various cases. And because of the mechanism of ``dispatch`` function, when I apply ``action.type`` and case ``GET_ITEM`` I dispatch ``getItems()`` function from my action to reducer.
84+
And the way, I invoke this function in my reducer is by doing the `action.type` and then applying various cases. And because of the mechanism of `dispatch` function, when I apply `action.type` and case `GET_ITEM` I dispatch `getItems()` function from my action to reducer.
8085
81-
By the mechanism of ``dispatch()`` - I am using dispatch() to send the type along with the data that we get from the axios request to the backend. And note, that the main function getItem() dispatches another function ( setItemsLoading ). This second function is called a thunk, and it returns the object/action. In the context of redux-thunk, a thunk is a second function that performs delayed logic by being asynchronously returned by a first function.
86+
By the mechanism of `dispatch()` - I am using dispatch() to send the type along with the data that we get from the axios request to the backend. And note, that the main function getItem() dispatches another function ( setItemsLoading ). This second function is called a thunk, and it returns the object/action. In the context of redux-thunk, a thunk is a second function that performs delayed logic by being asynchronously returned by a first function.

Redux/README.md

+20-2
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ This means that all data in an application follows the same lifecycle pattern, m
3030

3131
## An example of How data and state flows in Redux
3232

33-
Basically in React the `setState()` method is the initial and final step for changing the state and re-rendering the component. But with Redux this state changing will have to go through 5 / 6 different steps before state change can happen. Here's an example
33+
Basically in React the `setState()` method is the initial and final step for changing the state and re-rendering the component. But with Redux this state changing will have to go through 5 / 6 different steps before state change can happen. Here's an example. All these because in Redux all the application's state lives in one immutable state-tree called store. That store is at the fundamental level is a simple javascript object. And the reason its called **immutable** is because one does not simply modify the state tree. What we do is, we distribute action. **State is read-only**: The state cannot be changed directly by the view or any other process (maybe as a result of network callback or some other event). In order to change the state, you must express your intent by emitting an action. An action is a plain object describing your intent, and it contains a type property and some other data. Actions can be logged and later replayed which makes it good for debugging and testing purpose.
3434

3535
### 1> User types in an input box.
3636

37-
### 2> That calls an action-creator to get a well-formed action.
37+
### 2> That calls an action-creator to get a well-formed action. Action-Creator is just a function and creates an object.
38+
39+
Object goes to the reducer, which in turn is just a function that takes an object. And what comes out of it is also just an object.
3840

3941
### 3> The action then is dispatched to Redux - Redux then inserts that action to a Root-reducer.
4042

@@ -43,3 +45,19 @@ Basically in React the `setState()` method is the initial and final step for cha
4345
### 5> That reducer returns a new state and given the old state and the action object, the new state becomes the stored state.
4446

4547
### 6> That store then is fed-back into React and calls forth the final updated state.
48+
49+
Again I’ll walk through a simple example to show how a user input could trigger a state change that is reflected by a different part of the screen.
50+
51+
The user clicks a button in the app and a component prop is called like a function.
52+
53+
The corresponding container dispatches an action. This happens because the prop (which was just called in the container) is tied to an action dispatcher using mapDispatchToProps (in the container).
54+
55+
A reducer ‘hears’ that action and runs a function which returns a new state with specific modifications.
56+
57+
The container ‘knows’ that state has changed and modifies a specific prop in the component as a result of the mapStateToProps function.
58+
59+
The component now has a prop that has officially changed due to a new state being generated, so if that prop is responsible for any any visible UI, the user will see it change automatically.
60+
61+
#### Further Reading
62+
63+
[https://medium.com/@holtkam2/react-redux-understanding-the-data-flow-fd700b6bd56f](https://medium.com/@holtkam2/react-redux-understanding-the-data-flow-fd700b6bd56f)

Redux/Reducers.md

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1-
### Reducers - Absolute Bas
1+
### Reducers - Absolute Basic
22

33
### Reducer is just a function that takes two arguments A) Action (which is just a plain JS object preferably with type property ) and B) It takes the current state of your application. And then new state of the world comes out as the output of reducers.
44

55
### And how the action object is created - by something called Action creator, which is a function and the purpose of which is to create objects. So Action Creators creates objects -> Objects goes to Reducers (which is just a function) -> And ultimately what comes out, is the new state which is just an object.
66

7+
### The Action Creator.
8+
9+
In this file, you will write the functions that dispatch an action. These functions will be linked to your component props by the container’s mapDispatchToProps function. At that point, a component should be able to call a prop like a function and know that it will lead to an action getting dispatched. After the action is dispatched, it will be heard by only one type of function: the reducer.
10+
11+
The Reducer is the last step of the process of user-input generating a state-change and rendering the changed state back to the view. After ‘hearing’ an action get dispatched, the reducer can now generate a new state based on what the action wants it to do. Note the the state never actually changes in Redux, but instead the reducer generates a new state which is a copy of the old state, but with some sort of modification.
12+
713
<img src="reducers.svg">
814

915
1> https://redux.js.org/basics/reducers
@@ -24,10 +30,9 @@ Call non-pure functions, e.g. Date.now() or Math.random().
2430

2531
For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.
2632

33+
2> https://daveceddia.com/what-is-a-reducer/
2734

28-
2> https://daveceddia.com/what-is-a-reducer/
29-
30-
Redux is basically a fancy ``Array.reduce`` function. A Redux reducer function has this signature:
35+
Redux is basically a fancy `Array.reduce` function. A Redux reducer function has this signature:
3136

3237
## (state, action) => newState
3338

@@ -37,7 +42,7 @@ As in: it takes the current state, and an action, and returns the newState. Look
3742

3843
Plainly speaking, a Redux reducer gets to decide how each action affects the state.
3944

40-
## 3> Reducers Must be Pure Functions
45+
## 3> Reducers Must be Pure Functions
4146

4247
In order to achieve deterministic state reproduction, reducers must be pure functions. No exceptions. A pure function:
4348

@@ -52,4 +57,3 @@ Array parameters are also references. You can’t just `.push()` new items to an
5257
[https://medium.com/javascript-scene/10-tips-for-better-redux-architecture-69250425af44](https://medium.com/javascript-scene/10-tips-for-better-redux-architecture-69250425af44)
5358

5459
## Reducers shouldn't perform any side effects like API calls or router transitions. These should happen before an action is dispatched.
55-

Redux/applyMiddleware.md

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
### Redux is a small library. And exactly how small is it. [Its just 5 methods](https://github.com/reduxjs/redux/tree/master/src)
22

3-
43
### applyMiddleware()
54

65
### bindActionCreators()
@@ -11,7 +10,4 @@
1110

1211
### createStore()
1312

14-
So here, lets understand the ``applyMiddleware()`` function. The official dox is [here](https://redux.js.org/api/applymiddleware)
15-
16-
17-
13+
So here, lets understand the `applyMiddleware()` function. The official dox is [here](https://redux.js.org/api/applymiddleware)

Redux/container-component.md

+7-1
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,10 @@ The container component that knows about redux and dispatch and store and state.
66

77
The wrapped-component (i.e. which is not a container) in the pattern, which does the rendering doesn't need to know about any of that stuff: it gets its method to call via its props.
88

9-
And ... mapDispatchToProps was the useful means that redux provides to let the container-component easily pass that function into the wrapped component on its props.
9+
And ... mapDispatchToProps was the useful means that redux provides to let the container-component easily pass that function into the wrapped component on its props.
10+
11+
The Container is a file that corresponds directly to a single component. **Think of it like a literal container that you put your component in to ‘upgrade’ it.** By using two container functions called `mapDispatchToProps` and `mapStateToProps`, you can now link up your component’s props to state and action dispatchers (which are used to change state). If you had a div in your component that you want to display a property of state, you can simply make that div display a prop and then use mapStateToProps to link up that prop to state. If you want your component to store something in state, you can create a prop, call it as a function, and then use mapDispatchToProps to dispatch an action.
12+
13+
#### Further Reading
14+
15+
[https://medium.com/@holtkam2/react-redux-understanding-the-data-flow-fd700b6bd56f](https://medium.com/@holtkam2/react-redux-understanding-the-data-flow-fd700b6bd56f)

Redux/createStore.md

+19-14
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,38 @@
1-
1> We create a store, using the **createStore** function. We pass it our reducer, and then use the compose function to create a single function from two other functions. I won't get too much into how it works, but it takes other middleware and returns a single enhancer function from it. We are creating our middleware using the applyMiddleware function and passing it our thunk library.
1+
1> We create a store, using the **createStore** function. We pass it our reducer, and then use the compose function to create a single function from two other functions. It takes other middlewares and returns a single enhancer function from it. We are creating our middleware using the applyMiddleware function and passing it our thunk library.
22

33
```js
4-
import { createStore, applyMiddleware, compose } from 'redux';
5-
import { Provider } from 'react-redux';
6-
import thunk from 'redux-thunk';
7-
import reducer from './reducer';
8-
9-
const store = createStore(reducer, compose(
10-
applyMiddleware(thunk),
11-
window.devToolsExtension ? window.devToolsExtension() : f => f
12-
));
4+
import { createStore, applyMiddleware, compose } from "redux";
5+
import { Provider } from "react-redux";
6+
import thunk from "redux-thunk";
7+
import reducer from "./reducer";
8+
9+
const store = createStore(
10+
reducer,
11+
compose(
12+
applyMiddleware(thunk),
13+
window.devToolsExtension ? window.devToolsExtension() : f => f
14+
)
15+
);
1316
```
1417

1518
https://scotch.io/courses/getting-started-with-react-and-redux/setting-up-the-redux-store
1619

1720
2> [Official Doc](https://github.com/reduxjs/redux/blob/master/docs/api/createStore.md)
1821

1922
# `createStore(reducer, [preloadedState], [enhancer])`
23+
2024
Creates a Redux that holds the complete state tree of your app.
2125

2226
There should only be a single store in your app.
2327

2428
#### Arguments
2529

26-
1. `reducer` *(Function)*: A **reducing** function that returns the next state tree, given the current state tree and an **action** to handle.
30+
1. `reducer` _(Function)_: A **reducing** function that returns the next state tree, given the current state tree and an **action** to handle.
2731

28-
2. [`preloadedState`] *(any)*: The initial state. You may optionally specify it to hydrate the state from the server in universal apps, or to restore a previously serialized user session. If you produced `reducer` with `combineReducers`, this must be a plain object with the same shape as the keys passed to it. Otherwise, you are free to pass anything that your `reducer` can understand.
32+
2. [`preloadedState`] _(any)_: The initial state. You may optionally specify it to hydrate the state from the server in universal apps, or to restore a previously serialized user session. If you produced `reducer` with `combineReducers`, this must be a plain object with the same shape as the keys passed to it. Otherwise, you are free to pass anything that your `reducer` can understand.
2933

30-
3. [`enhancer`] *(Function)*: The store enhancer. You may optionally specify it to enhance the store with third-party capabilities such as middleware, time travel, persistence, etc. The only store enhancer that ships with Redux is `applyMiddleware()`
34+
3. [`enhancer`] _(Function)_: The store enhancer. You may optionally specify it to enhance the store with third-party capabilities such as middleware, time travel, persistence, etc. The only store enhancer that ships with Redux is `applyMiddleware()`
3135

3236
#### Returns
33-
*`Store`* : An object that holds the complete state of your app. The only way to change its state is by dispatching actions. You may also [subscribe](Store.md#subscribe) to the changes to its state to update the UI.
37+
38+
_`Store`_ : An object that holds the complete state of your app. The only way to change its state is by dispatching actions. You may also [subscribe](Store.md#subscribe) to the changes to its state to update the UI.

0 commit comments

Comments
 (0)