After Using Redux-Thunk

Michael S
2 min readJan 23, 2019

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 :

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.

--

--