Where should I put API call which is requesting user data - reactjs

Where should I put get user data API call which is requesting user data such as username, email from JWT token stored in localstorage.
Should I call it from _app.js pass it to the components or should I create redux store and save these data.

Using redux only for that purpose is an overkill. You should create context and wrap components, which are using this data. Also there is hook called useReducer, combined with context API allows you to achieve redux behavior.

Passing user data down to components directly is not a bad idea if you have only 2 level depth structure which is often not the case.
For this purposes is a nice option to use tools like Redux or React Context API. That way you can access the global state from whichever component you like in the same way, which leads to more readable and maintainable code. For more information about Redux vs Context API, consider looking more in-depth to understand the differences and decide which one is more suitable for your case.
For me personally, the Context API can do the work in more of the cases which is fine. Also, it is already part of React, and it's not a dependency like Redux is.

Related

is there any use case for context api if an app already uses a tool like redux?

I'm not aware of any use case for using Context API if an app already uses a tool like Redux. Seems like Context API would only be useful for something quick and dirty where performance wasn't critical and the developer didn't know Redux. Does this seem like an accurate assertion? Ie if an app is already implementing Redux then there's no additional use case which would justify the use of Context API?
"Is there any use case to use context api if redux is already in place for an app?"
Yes, there is/are. Context API is a mechanism used to share data (including state) between React Components. Redux is a State Management tool.
You can have both Redux (for managing state) and Context sharing data (different from Redux state) between Components.
Here's a real life open source React app using both Redux and Context API at the same time.
Recommended reading: Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux)
The Context API allows you to pass a value down from any component (anywhere in the tree) to all of its descendents. Redux manages a single global state. This is completely different.
Here is a concrete example where you need the Context API even though you are using Redux: let's say that you are designing a timeline-like page containing many Posts (each post having an id allowing you to look it up in the Redux store), and each Post component contains a lot of sub components, to show for instance the title, the content, the likes, the comments, the tags, etc.
All of these sub components need access to the post id in order to get the right data from the Redux store. You could pass it directly from the parent Post component to all of the children (and grandchildren, etc), but this may get annoying, so rather than prop-drilling you can instead wrap each Post in a Context with the post id as a value, and then all of the children and grandchildren can use the context value directly without any prop-drilling.
There is no way you can solve this problem with Redux, because it relies on having separate contexts for each post.

use of Context alongside Redux

I am using Redux heavily in my application. I also have a very limited number of properties stored in Context:
username of currently logged-in user
screen geometry information (to adapt whenever browser window resizes)
Is this an antipattern and should I move everything over to Redux and dispense with Context altogether? I am inclined to answering yes. So the question is:
Are there valid use cases for using both Context and Redux in the same app or is it a code smell?
No I can't think of a single reason why it would be a good idea to use both.
Generally "if you are using Redux only to avoid passing props down to deeply nested components, then you could replace Redux with the Context API".
If you need more advanced features, like predictable state container, async actions and so on, then choose Redux.
Pardon the pun, but "context switching" between the two is only going to confuse you, your app and future developers on your app.
in your case, username stuff definitely could belong in a redux reducer and screen geometry information feels like it is basic enough to live in React and be passed down as props. although, this of course can be stored in Redux state too

Is there a way to access Context in a Redux Thunk?

This is more of an understanding question and I also want to know the community thoughts, rather than a code question.
We have a React App using redux for managing the global store and redux-thunk for dispatching actions. Now we want to localize the App and add a language switch. For that purpose I created a HOC which uses React.Context to store the dictionary for current language in it. And I wrapped all Components in this HOC - everything works just fine.
But we also need to access to the dictionary in the thunks to e.g. provide success/error messages after API calls in the selected language. It seems to be impossible without passing dictionary into thunks.
I've read a lot about Context API and when to use it and that it has different purpose than Redux. That's why I put the translations in the Context and not in the store, mainly for this reason. But now I'm getting the feeling that I missed something and should actually put the translations in the store instead to not be forced to pass the dictionary to the thunk every time I need it there. Is it so?
Or is there a way to implement something like getContext similar to getState from redux-thunk?

React + Redux App: Calling API through a Redux action Vs Calling an API directly

I'm working on a React+Redux application. I'm calling APIs through Redux actions and storing the response data in the Redux state. But there is a case, Where I don't have to store the API response data in the Redux store.
So the question is, Is there any valid reason to call the APIs through
Redux actions or Should I call the APIs directly since I'm not storing
the response data in Redux store?
It depends on what kind of call you're trying to make, and who's concern it is.
Here are a few cases:
Is this a one-way call to track something?. You can fire an action that gets picked up in a middleware. this is a good case for sending analytics.
This doesn't have to be stored in Redux's store.
Is this a call where some other part of your application will need this data?, then this is a good use case for making an update in the Redux Store so other components when read this and use props to decide what to render etc.
Is this a call where it only concerns one component or isolated part?. You can make this call inside the component in componentDidMount since this doesn't concern anyone else
Alternatively take a look at Sagas, they observe all actions that get dispatched and decide what to do with them in a clean way.
The accepted answer quite well explains the scenario where from API call can be initiated. For better user experience, we always show some spinner or busy sign to inform the user that a request is being made and it has not finished yet. It may happen that API response is not mutating the state, but to let the user know some task is going in the background, we usually update store (for global access) or state (for component level access) with value like isFetching or anything meaningful.
So, it depends on the developer, whether he/she want to show some busy sign or silently perform the API request. Moreover, if they want to show busy sign then, they should decide which part of the application should be aware of the API call. If it is restricted to the component level only, then no need to make the call in actions, otherwise, for global level, yes it should be inside action.
For the sake of uniformity, you should always follow the redux way, even though all the responses are not stored in Redux. It is also a question if you are not using the response from an API call why are you making the call. This argument is counter-intuitive. If you are using the response in some way better do it the Redux way. It is advised to always store the response to a call to Redux and use it, I am sure you are making API calls to do some action on UI.

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.

Resources