tmp dev
tmp dev

Reputation: 9193

Redux equivalent for Angular2 services

I come from an Angular2 world where there are services that do the normal data loading and so on, now I am on a React, Redux application and am trying to figure out what is the equivalent to Angular2 services in Redux (React). Is it Redux-thunk?

Upvotes: 1

Views: 684

Answers (1)

Ming Soon
Ming Soon

Reputation: 1018

The answer is yes and no.

Yes

  • Angular services have the logic to load data and normally return a Promise object that gets resolved with data loaded.

  • With Redux Thunk middleware, you create asynchronous action creators where you put the logic for data loading. But instead of returning a Promise object directly, it waits until the data gets resolved and dispatches an action to update the state with data loaded. React components receive data from Redux store via props. (See connect() method from react-redux.)

No

  • Angular services are singletons that provides a specific functionality, like $http for facilitating communication with the remote HTTP servers.
  • Redux Thunk is a middleware and does not do anything but to allow you to write asynchronous action creators that can delay the dispatch of an action, or to dispatch only if a certain condition is met. The action creators are functions that create actions - they are not intended to provide other functionality, like communication with backend servers.

With that said, it is often a matter of coding style where and how you write the logic to load data.

You can use the Fetch API or its polyfill function, or axios library, both are Promise based. You can also consider using Observables, but it is beyond the topic, I think.

As you do with Angular services, you can put all the related logic in a single location and export them. In your action creators, you call these wrapper/helpers, listen for resolution/rejection and dispatch an appropriate action with data resolved as a payload.

Your reducers update the Redux store upon receiving an action dispatched and these state changes are propagated to React components. And this is how the Flux architecture works and how the data flows from Redux Store to React components, AFAIK.

(I might be wrong, please correct me if anything is incorrect and I am open to your opinions. I am still on the way to figure out the best practice to implement services in React applications.)

Upvotes: 3

Related Questions