Want to properly make REST calls from ReactJS + Redux application? The simpliest way, is to do it using redux-thunk package. This package is an redux middleware, so first of all, you should connect it to redux:
1 2 3 4 5 6 7 8 | import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers/index'; const store = createStore( rootReducer, applyMiddleware(thunk) ); |
This allows you to dispatch async actions along with regular sync actions. Let’s create one of them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // actions.js export function fetchTodos() { // Instead of plain objects, we are returning function. return function(dispatch) { // Dispatching REQUEST action, which tells our app, that we are started requesting todos. dispatch({ type: 'FETCH_TODOS_REQUEST' }); return fetch('/api/todos') // Here, we are getting json body(in our case it will contain `todos` or `error` prop, depending on request was failed or not) from server response // And providing `response` and `body` variables to the next chain. .then(response => response.json().then(body => ({ response, body }))) .then(({ response, body }) => { if (!response.ok) { // If request was failed, dispatching FAILURE action. dispatch({ type: 'FETCH_TODOS_FAILURE', error: body.error }); } else { // When everything is ok, dispatching SUCCESS action. dispatch({ type: 'FETCH_TODOS_SUCCESS', todos: body.todos }); } }); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.