How and where to fetch data in react [duplicate] - javascript

This question already has answers here:
Where to place logic for loading initial server data in React app?
(2 answers)
Closed 5 years ago.
How do I do AJAX requests in React? React itself doesn’t have any allegiance to any particular way of fetching data. Which hook in react is best to fetch the data [constructor, componentdidmount] or have a custom hook [static method].

The place you should be calling you AJAX requests depends on your functionality,
If you need you AJAX call when the component is mounted or at repeated interval, you should call it within a componentDidMount function. An example could be fetching data a regular intervals from your server to update on screen.
If you want to send an AJAX request on an event, you should have it in your custom function. An example could be posting the input values to your backend api
In order to make AJAX calls, you can make use of axios, fetch npm packages

There is not any particular place of fetching AJAX request in React. It depends on your functionality mostly. Until now I've made AJAX calls inside of 'ComponentWillMount' method to make ready data asap.
Also, sometimes I've needed to fetch data from server after a component did mounted. So in that case, I had to use this workaround: React - setState() on unmounted component
The most important topic is here not blocking the rendering interface and to set properly the state, after getting data from server.

Related

How to do background sync instead of fetch requests on UI changes?

For example, let's take a simple web application with comments feature. In my understanding, when a user posts a new comment, the following would occur:
display UI loader;
update the front-end state;
send a fetch request to the API to post a new comment;
Wait for the response;
send another fetch request to the API to request the new list of comments;
waiting;
update the front-end state with new comments;
update UI to reflect the new state with a new comment;
And the user needs to wait while front-end app interacts with back-end on almost every data change. The same way we did it earlier with PHP/Python/Ruby, ajax, server-side rendering and templates.
That makes me think what's the point of adding so much front-end complexity with something like react, when the result is basically the same.
My question is: are there any alternative approaches to this? Is it possible instead to do the above case the following way:
user clicks to post a comment;
update the front-end state;
update UI to reflect the new state with a new comment;
sync front-end state with API DB in the background;
Well, as your question is tagged react, you could use the Apollo library (it is intended to work together with graphql on the backend) for data fetching. It offers a feature called Optimistic UI, which will be update the frontend with the respected result, until it receives an answer from the backend. If the expected result differs from the received one, the component will change the UI automatically to the real result. In case of an error, it will show an error message.
You definitely could, your first method is just way of doing it.
Apart from 'syncing' your front-end state, another method is also to just pre-emptively update the UI (step 7 & 8 in your first method) before doing step 3-6, and only reverse the action if the API call failed. This should allow for slightly better UX for the end-user too.
I get it that you think it's waste of time for users to wait until requests are successful. However, isn't it more important to stop users from keeping making bad requests to the server?
So, what I would do is just to stop fetching data from the database every after users make requests.
Fetching the DB data to begin with and store them in redux states
Make requests to the DB while holding users from doing anything
Make changes to the redux state if the requests are successful
But what you want to do could be done like this
Fetching the DB data to begin with and store them in redux states
Make changes to the redux state while making requests to the DB in the background
Depending on whether the requests fail or not, roll back the change users made from the redux state

React making api calls with componentDidMount()

I have a question about making api calls with react. They say to make them in the componentDidMount lifecycle method, but if the component is already mounted, do I have to re-render it again somehow? What if I am making a get request and the component displays some data that it gets? Thanks!
when you set state after making the request the component will rerender
This is actually why useEffect() in react hooks is both componentDidMount and componentDidUpdate; a lot of people will correctly implement componentDidMount, but they'll forget to implement componentDidUpdate and you end up with components that you need to remount in order for them to function correctly when they should be responding to the changes in props via componentDidUpdate.
You only need to use componentDidMount for (automatic) initial API calls made on page load, you can still make any API calls via a user interaction like a button click etc.
When your call completes within componentDidMount, set the state to store your result. This will trigger the component to rerender. If your component relies on information from an api call, consider using a loader and clearing it once the call is complete.

React API call outside useEffect

I was curious to know if making an API request outside of the lifecycle/useEffect is a valid way to make the call?
https://stackblitz.com/edit/react-useeffect-button has two functional components, the parent component makes an API call and passes the data to the child component, initially specified the limit of data to be fetched from the endpoint as 2 and the parent component has a LoadMore function that is passed as a prop along with the data to the child component.
Using the react-slick slider to display the images in the child component and the Load button onClick will call the function LoadMore inside the parent component and then it makes an API call and appends the new data from API to the old Data. The load button will append one Image to the existing images.
is this a good way to make API requests or should it be done only in the lifecycle methods?
is this a good way to make API requests outside useEffect/lifecycle.?
It depends on your requirements.
should it be done only in the lifecycle methods?
It depends on your requirements.
There's nothing wrong making API request outside useEffect. But it should be done in some other function or it will cause the request to go on every re-render.
And if the response if being saved in a state variable.
Then it will go into the infinite loop.
When do we make the request in useEffect and when by some other function?
Requests that fetch data or send some info at the time of initialization of the component is supposed to be made in componentDidMount/useEffect
And requests that are supposed to be sent on some action (like in your case, onClick) so they are hit according to that event.
There's neither good or bad, it's all about your requirements.
If you are making an API call to get data from initial render then using a lifecycle hook is a good approach. In your scenario, you want to make an API request when hitting a button. In that case it can be a simple function without any lifecycle hook method.
The only key part here is that you are maintaining the state and rendering the view from the state.
This depends on your needs.
if you think whenever your params change,API call will be triggered.
in this case, you should set the API call inside the useEffect.
If you want your API call triggered on page load(ComponentDidMount). In this case, you should set API call inside the useEffect
Otherwise no need to set api call inside useEffect.
In your case no need to set API call inside useEffect. because you hit the API call when the user clicks the button. So no need to use useEffect.

Why React recall API when use Server side rendering?

I'm trying to using server-side render for my React web application (redux + react-router).
Server returned rendered HTML properly with API call on the server side.
But when browser receives the HTML document, it recalls API second time.
So it makes API call twice: 1 on server and 1 on the client with same result data.
Why client recall the API and How to avoid that duplicate call?
Check if the html returned contains script which calls the server. If that's the case, you have to either:
Modify this call to receive this piece of data in an asynchronous way, so the page doesn't get reloaded
Modify the returned HTML page, so it doesn't execute any further calls
It's a bit hard to speculate without an example

Best practice react, redux, multiple async calls

I have a react contain that makes an ajax request via #asynConnect. Once that data comes back from the server, this component's render method will conditionally render several components. Some of these components have their own data that is required to render their content. What is the best way to fetch the data for each child component? Do I use componentWillMount? Should my parent container dispatch another action that when received will make the subsequent ajax calls? Should I use some type of middleware (redux-thunk)? I've read multiple posts and comments on this topic and still not sure if I've come across a "best practice". FWIW I'm using this project: https://github.com/erikras/react-redux-universal-hot-example

Categories

Resources