Reputation: 9193
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
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
$http
for facilitating communication with the remote HTTP 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