Refresh page automatically in react js - javascript

I have a react js application to show data using an Axios GET call. I want to update my data automatically by repeating the GET call, and not using a refresh button. I could add a timer to do this. I have only a post call from an external server to send on my react js app URL. Could you suggest me a workaround?

You can use setInterval() function in JavaScript to repeat the GET call after a specific interval.
Here you go -
useEffect(() => {
const interval = setInterval(() => {
axios.get(`your-url`)
.then(res => setData(res.data))
.catch(err => console.error(err));
}, 5000); //set your time here. repeat every 5 seconds
return () => clearInterval(interval);
}, []);

The way I see it, there are 3 options available to you.
Option 1: Would be to have WebSockets available in your API and connect your react app to them. Whenever the data is updated the app receives and "update" with the changes. This is the best option if you (or your team) are the devs for the backend/API.
Option 2: Having a button that redos your request would be the easy option. The user can always re-request whenever they want.
Option 3: Re-requesting from time-to-time can be achieved by using setInterval(). Which most people would not recommend unless 100% necessary. This method can be harmful for various reasons.
You're requesting multiple times, not sure if changes were made, wasting bandwidth and clogging your API with "useless" requests
If the API isn't yours, they can block your app from accessing due to multiple requests being made

Related

React Query dynamic incremental queries

I am currently fetching data from a 3rd party api in a React application.
The way the api is structured, the flow goes like this:
// Get a list of data
response = GET /reviews
while response.data.nextPageUrl is not null
response = GET ${response.data.nextPageUrl}
I currently have this logic inside of a "fetch method"
const fetchMyData = () => {
// The logic above
}
const query = useQuery(['myKey'], () => fetchMyData, {...})
This works, but comes with some drawbacks.
There is no way to see the progress of the individual requests (to be used in a progress bar)
It cannot leverage React Query's caching functionality on an individual request.
For example: If there are 10 requests to be made, but during the 5th request the user refreshes the page, they will need to restart from the beginning.
I am aware of useQueries but since I do not know the query urls until I have received the first request I do not see how I could use it.
Is there a better approach or way to satisfy the 2 issues above?
Thank you in advance
What you need is Infinite Queries. useInfiniteQuery works similar to useQuery but it's made for fetching by chunks. useInfiniteQuery has extra parameters like getNextPageParam which you will use to tell React Query how to determine the next page. This hook also returns fetchNextPage, hasNextPage (among others), which will allow you to implement patterns like a "show more" button that appears for as long as there is a next page.
By using infinite queries you still leverage on React Query caching. Check the docs for more info.

How can you guarantee that a PWA is fully up-to-date using only built-in functionality, without reloading the page? [duplicate]

I'm working on adding a requested feature to my SPA. We have some users who leave their tabs open to our application for long periods of time. We also push out frequent updates (sometimes 5x a day, as we're pre-revenue). I'm wondering if it's possible to modify the serviceWorker that comes installed with Create-React-App to run a polling loop (maybe every 10 minutes) to poll for new updates to the application, instead of only on initial page load.
This way, a user who leaves their tab open could receive update notifications without having to refresh.
Has anyone achieved something like this before, and know how I might implement that into the CRA serviceWorker?
Figured it out! In the registerServiceWorker.js file, I added a simple setInterval inside the callback for the navigator.serviceWorker.register() function:
// poll for live updates to the serviceWorker
pollingLoopInterval = setInterval(async () => {
await registration.update();
}, POLLING_LOOP_MS);
Easy!

How to notify without websocket

I want to integrate a simple notification system in my react application. I want to notify for example:
- new post (when the user post the system need time to transcode the media attached and the publication)
- missing settings (the user need to compile some information)
- interesting posts etc..
There is a simple way to add a websocket, like socket.io, to a reactjs app with an aws lambda backend?
All the notification not need to be read in real time, maybe an ajax call every 2 minutes can solve my problem, but, in this case, someone can help me avoid ajax call if the app isn't used(like if the app remain opened in a foreground tab...)
componentDidMount() {
this.liveUpdate()
setInterval(this.liveUpdate, 120000);
}
liveUpdate() {
axios.get(endpoint.posts+'/live/', cfg)
.then(res => {
// ...
});
}
This code is in the footer component, the call happen every 120 seconds, but the call will still happen also if a user leave the application opened in the browser and not use it, this on a lambda backend mean a waste of money.
There are 3 main ways of notifying that I can think of at the moment...
Long polling (using ajax etc)
Websocket
Push Notification
Push (though) requires permission from the user

React/Redux - When should you fetch new data from an API to update your store?

I'm trying to get a handle on what is best practice when it comes to updating/refreshing your Redux state with data from an API.
Think of this scenario:
You have a To Do app where a number of users are potentially updating the same To Do's as you at any given point in time. Obviously you'll want your local Redux store to reflect these changes from the other users eventually.
Would you:
Fetch the updated set of To Do's on route change?
Fetch an updated version of that To Do when/if the user makes changes to the To Do or interacts with it?
Both?
Never - you keep the state in the store once fetched and it becomes the source of truth for that session (obviously not ideal)
Something else?
I'm not interested in pushing changes to the client right now nor polling an API (ugh!). I'm simply interested in gaining some sort of consensus as to when most developers refresh API derived data that is stored in their Redux state.
If you don't want to push nor poll, then fetch data when the user request it. Never fetching may be well suited for edge case application but definitly not a common use case.
This is what I got from your question
Same space in your app is updated by multiple user.
Any user who is on the app must get the changes done by other user.
You want to know when to fetch data or refresh your store.
I'm not interested in pushing changes to the client right now nor
polling an API (ugh!).
I am not getting it what is this for. You may not be updating the app but to see the changes your app should be updated by one or other.
Apart from this I told you to subscribe the fetching of data wherever you are fetching it. I don't know what you understood by subscription, according to me subscription is to keep on doing fetching at regular interval to get updates. Subscription is async in nature.
I am giving a simple example of implementing subscription.
console.log("Started");
let subscription = false;
const getData = () => {
// call your database and fetch the data and once
// fetching done call the getData again
// Think setTimeout as database call.
// upon resolving the data I called it again
// It neither stops other call back from running run
setTimeout(() => {
console.log("Fetching");
if(subscription) {
console.log("shuting");
return;
}
getData();
}, 1000);
}
getData();
setTimeout(() => {
console.log("hello");
}, 5000);
setTimeout(() => {
subscription = true;
}, 8000);

SOCKET.IO analogy in angular application (with rx.js)

I am developing angular(2) application.
And I want to update view when data changed in back end.
getData() {
return this.http.get("some url")
.map(result => result.json());
}
How can I develop listener in my component, which will be listen and updating view?
So, two solutions depending on what you are able to do:
1 - You have write access to the server's code
Then you can implement the websocket support on your server and then use a tool like https://github.com/ohjames/rxjs-websockets to automatically wrap the socket events in rxjs observables.
2 - You don't have write access to the server's code
Well, in this case, you will have to do a regular polling of the server. Which would look something like that:
Rx
.Observable
.timer(0, 1000) // once every second
.mergeMap(_ => this.http.get("/url").map(json => result.json()))
If the server is well implemented (and you send the right headers), it might send you back a 304 http code from which you can deduce that nothing happened since your last call, and you can filter out those cases.
Hope it helps

Categories

Resources