Before using Redux-Thunk & After using Redux-Thunk
Before :
- Action creators must return plain JS objects with a type of property
- By the time our action gets to a reducer, we won’t have fetched our data!
- Logic below is breaking a rule of redux : Actions must be plain objects
src/actions/index.js
export const fetchPosts = () => {
return async dispatch => {
const response = await jsonPlaceholder.get('./posts');
dispatch({
type: 'FETCH_POST',
payload: response
}) };
};
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import thunk from 'redux-thunk';import App from './components/App';
import reducers from './reducers';const store = createStore(reducers);
ReactDOM.render(
<Provider store={store} >
<App />
</Provider>,
document.querySelector('#root')
);
After :
src/actions/index.js
export const fetchPosts = () => {
return async dispatch => {
const response = await jsonPlaceholder.get('./posts');
dispatch({
type: 'FETCH_POST',
payload: response
}) };
};
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';import App from './components/App';
import reducers from './reducers';const store = createStore(reducers, applyMiddleware(thunk));ReactDOM.render(
<Provider store={store} >
<App />
</Provider>,
document.querySelector('#root')
);
Reference :
- https://redux.js.org/faq/actions#how-can-i-represent-side-effects-such-as-ajax-calls-why-do-we-need-things-like-action-creators-thunks-and-middleware-to-do-async-behavior
- https://redux.js.org/faq/actions#what-async-middleware-should-i-use-how-do-you-decide-between-thunks-sagas-observables-or-something-else
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
I am blogging what I’ve learned to find later here for myself. If you happened to read this shit and there is wrong information, it would be appreciated to add a comment below.