I'm using ReactJS + Redux, along with Express and Webpack. There is an API built, and I want to be able to make REST calls -- GET, POST, PUT, DELETE -- from the client-side.
How and what is the properly way to go about doing so with the Redux architecture? Any good example of the flow, in terms of reducers, action creators, store, and react routes, would be extremely helpful.
Thank you in advance!
The short answer is:
redux-thunk
andredux-saga
, as others have said.For a brain-dead simple library that you can drop in to your redux app, you could try redux-crud-store. Disclaimer: I wrote it. You could also read the source for redux-crud-store if you are interested in integrating the fetch API, or another API client, with redux-saga
This is the primary use case for libraries like
redux-thunk
,redux-saga
, andredux-observable
.redux-thunk
is the simplest, where you would do something like this:The above example is taken directly from http://redux.js.org/docs/advanced/AsyncActions.html which is really the definitive source for answers on your question.
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:This allows you to dispatch
async
actions along with regularsync
actions. Let's create one of them:I prefer to separate react components on presentational and container components. This approach was perfectly described in this article.
Next, we should create
TodosContainer
component, which would provide data to presentationalTodos
component. Here, we are usingreact-redux
library:Also, you should create
todosReducer
, which will handleFETCH_TODOS_SUCCESS
action, and other 2 actions if you want display loader / error message.For other operations like
CREATE
,UPDATE
,DELETE
there is nothing special, they are implementing the same way.