When to use Redux Thunk? - reactjs

I was using axios for api calls in class component of React. And used Redux to store mostly login details.
So started learning about Redux-thunk and now I am confused as to where to do API calls? Is doing api calls from view side not good? Do i need to use redux-thunk?

You use redux-thunk when you require async actions for your reducers.
Calling an API would be a good example of that. Doing API calls is something the view would do, anyways (e.g., otherwise you'd have them in your components, which is "view", too). The API is then doing the business logic and is only providing "view data".
Your view might also want to track the state of the async action (e.g. "list is loading...", "failed to load because xyz", "{list of users when loaded}")
You don't need to use redux-thunk, but chances are at some point you re-implemented it, anyways (I did that and then switched). I suggest you simply use #reduxjs/toolkit (They have a good documentation site)
It really eases up working with actions, thunks, async thunks and reducers in general.

Related

React Redux, why not we dispatch success and Fail action from event handler

I am learnig react and react redux, I just want to know that, suppose I have sign in page, there onSubmit we dispatch action SIGN_IN (of redux) , on action then we dispatch SIGNIN_SUCCESS and SIGNIN_FAILURE. So I just want to know that insted of handling SIGNIN_SUCCESS and SIGNIN_FAILURE on actions, can I handle it on submit handler function of Components.
So In this way I don't need redux think middleware, And there will be only sync actions.
Is this a good approch?
It's possible, but I can think of some disadvantages for this approach:
Separation of concerns, or the general intended structure of react-redux apps, envisions dealing with async actions outside of components. Async actions can potentially do complex things and it's cleaner to keep this out of components. They don't need to know about the details of handling errors on sign in (for example).
Reusing this event handler would need to be react custom hook (since it uses dispatch), tying it into react for no real reason. Other places in your app might want to dispatch a signIn thunk as well.
Thunks have quick and easy access to getState. If that is needed, it's a bit more cumbersome to do the same in react and a bit weird to use useSelector with the entire state.
Since redux-toolkit is now the recommended way to use redux, the createAsyncThunk it offers makes the typical thunks more concise. You get the pending/fulfilled lifecycle around a promise out-of-the-box. It's probably better to rely on this rather than re-inventing classic thunks in a different way (what you had in mind with sync actions).

Asynchronous behaviour in redux

I was working on creating the react-redux application. But stuck on the point why we shouldn't call the async function (for API calling) in the component method like componentWillMount etc? Why I've to use the middleware like redux-thunk & saga? Why we cannot call the API request from the action and based on that result, we call the reducer? Is it the bad idea? I didn't understand deeply about this. Can you please help me out to understand the concept of API calling in redux?
As far as I see it, you can call async functions anywhere, including in componentWillMount. What a middleware like redux-thunk does, is to add IDs in the dispatched actions, 'ordering' them, avoiding race conditions such as the one that is described in Writing Async Code in redux

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?
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.)

When using redux, why should I avoid doing API calls directly in the component?

So I may be asking the wrong question, so please leave comments and I'll adjust. I was told by another developer that when using redux, I should do ALL API calls within actions and create reducers for them. But I feel that sometimes making the call directly in the component will save me a TON of code. Are there best practices for this sort of thing?
If the data you are getting from the API is only going to be consumed by a single component then you are fine to write it as part of your component (or better still, a container component). I believe the rationale behind doing your API calls in actions is to ensure that the single source of truth is maintained (the main reason to use 'the react/redux way' for me personally). If you are bringing in data from your API that is to be consumed by multiple components then use redux to ensure the same state is maintained by redux and passed to all components that use it.
This was previously answered by Redux's creator, Dan Abramov, here: Why do we need middleware for async flow in Redux? .
The summary:
It’s just inconvenient in a large application because you’ll have different components performing the same actions, you might want to debounce some actions, or keep some local state like auto-incrementing IDs close to action creators, etc. So it is just easier from the maintenance point of view to extract action creators into separate functions.

What are the differences between Redux-Thunk and Redux-Promise when used with Axios apis?

I have been using React , Redux since few months now. One of the most confusing part of the ecosystem is the async data flow. There are many great solutions available and choosing the right solution for your problem is the tough part.
In my application, the action creators mostly have async axios [ajax] calls to my back-end apis. Injecting Redux-Promise as a middleware resolves the issue of async data flow.
Considering the scalable app, I might need to chain multiple axios calls in my action creator. I think I can still use Redux-Promise as a middleware and this would take care of async data flow in my app.
In general the team is more inclined towards using Redux-Thunk, which I feel more complicated syntax for this problem. I need suggestions in evaluating these 2 frameworks considering most of my action creators are making axios calls(promises) only. I have seen a great deal of discussion on Redux-thunk here. I understood how thunk can be useful. . But I need more clarification evaluating Redux-Promise and Redux-Thunk together when used for Promises only. Which middleware is better in such situation and why? What advantages do I get using Redux-Thunk over Redux-Promise ? Or there is none?
Redux Promise is convenient for dispatching three actions (request, success, failure) without writing that code manually.
Redux Thunk is convenient for async data flow when you express one action creator as waiting for another action creator. It also lets you read the current state for conditional dispatches and early bailouts.
You can use them together, or use any one in particular. I would recommend starting with Redux Thunk because it offers more control and is more versatile. After you get it working, you can consider adding Redux Promise to remove some of the boilerplate code related to dispatching three kinds of actions. If you find that it doesn’t buy you much, remove it. On the other hand, if you notice all you thunk action creators just dispatch a single promise, you can remove Redux Thunk instead.
If this is still confusing, I recommend just using Redux Thunk until you get more comfortable with how middleware works.

Resources