I have a React Native app where, on one screen, I have a useEffect hook that constantly fetches data from a site and updates my local variable with that data (see below for a simplified example). The problem I am running into though is that this is killing the performance of my app. Even if you leave this screen, the app is sluggish.
The issue is no doubt caused by the countless calls to the URL to get the data & constantly resetting my local variable with the data. I tried using a dependency array with the hook, but if I do that it doesn't continually update, it only updates on the first load of the screen and I need it to update whenever there is a change (whenever new data is available).
Is there a way to do this so that I constantly get any updates from the remote source but don't slow down my app?
const [retrievedData, setRetrievedData] = [{}];
useEffect(() => {
let fetchedData;
fetch(
'https://site-with-data.com',
)
.then(response => response.json())
.then(json => {
setRetrievedData(processData(json.events));
})
.catch(error => console.error(error));
});
When useEffect doesn't have a dependencies array (the second argument), it will run on every render. That is why you are making so many calls.
If you need to update the data real-time, the first question you must answer is: how will the client know the data has changed in the server?
One way you could make the server notify the client is by using WebSockets. A WebSocket creates a bidirectional connection between the client and the server, and the server can notify the client whenever anything changes. Other than that, you could also use a technique called "long polling" or "server-sent events".
But any of these three solutions would require you to change your server (in addition to your client).
Quick fix: limit the update frequency to "refresh every N seconds"
The quick and dirty alternative without changing the server is just to decide a frequency (e.g., update every 5s) and go with it in the client.
Example:
useEffect(() => {
const intervalId = setInterval(() => {
fetch(
'https://site-with-data.com',
)
.then(response => response.json())
.then(json => {
setRetrievedData(processData(json.events));
})
.catch(error => console.error(error));
}, 5000); // update every 5s
return () => clearInterval(intervalId);
}, []); // add to this array any variable that affects the fetch (e.g., URL)
Which number of seconds should you use? That will depend on each case. To decide that, evaluate both UX and server load.
Related
I have weird results displayed in the web console:
fetch() is sending duplicated requests to the same url.
I thought it could be something related to fetch(), but also noticed that on reload of the app (quasar, based on webpack) also the requests to the http://localhost:8080/sockjs-node/info are duplicated.
By contrast, I noticed that requests handled by jQuery are NOT duplicated and works fine.
I cannot say if it is an error due to webpack configuration, fetch or they way I am using it i Vue components.
E.g. This article points out possible causes https://insights.daffodilsw.com/blog/how-to-avoid-duplicate-api-requests but in my case it is not due to user interaction : requests are triggered at time of relaunching the app (webpack), and particularly the stack trace shows that the requests are fired at time of creating the components, just multiple times.
Example of how I am using fetch():
// component -
methods : {
search(input) {
return new Promise(resolve => { // a new promise is request multiple times, in spite in created() it is called just once
var _base = 'myEndpoint/api'
const url = `${_base}fuzzyautocomplete?q=${encodeURI(input)}`
if (input.length < 3) {
return resolve([])
}
fetch(url) // so promises are actually different, and duplicated requests are fired by fetch
.then(response => response.json())
.then(data => {
console.log(data)
// resolve(data.query.search)
resolve(data)
})
})
},
....
// and it should be called just once at time of creation
created() {
this.search('init first query !!');
}
Could you advise?
If I am rendering a page with Nuxt, Vue, and Axios - is there a way to reuse the asyncData request (or data)?. For example, if I render a response, and the user takes an action on the page to filter, sort, etc. the data, can I reuse the same data to render again - or do I need to make a new call in mounted?
export default {
asyncData ({ env, params, error }) {
return axios.get(`${env.cockpit.apiUrl}/collections/get/cat_ruleset?token=${env.cockpit.apiToken}&simple=1&sort[ruleid]=1`)
.then((res) => {
return { catrules: res.data }
})
.catch((e) => {
error({ statusCode: 404, message: 'Post not found' })
})
},
mounted() {
},
methods: {
}
}
Of course you can reuse it. The simplest way would be to store the result somewhere (anywhere, really, but your store would be a good storage candidate) and change your method to:
asyncData ({ env, params, error }) {
return X ? Promise.resolve(X) : axios.get(...)
}
... where X is the stored result of your previous call.
But you don't have to.
Because, by default, the browser will do it for you. Unless you specifically disable the caching for your call, the browser will assume making the same call to the server will yield the same result if you do it within the number of seconds set in max-age of Cache-control.
Basically, the browser returns the previous result from cache without making a call to the server, so the optimization you're after is already performed by the browser itself unless you specifically disable it.
You can easily spot which calls were served from cache and which from server by looking in the Network tab of DevTools in Chrome. The ones from cache will have (memory cache) in the Size column:
... and will have a value of 0ms in Time column.
If you want control over when to call the server and when to serve a cached result — most browsers have a limit on max-age (see link above) — you could (and should) store the result of your previous call and not rely at all on the browser cache (basically the internal check inside the method, which I suggested at the top).
This would enable you to avoid making a call long time after the cache max-age has passed, because you already have the data, should you choose to do so.
Although I know this may not be considered as a best practice, but what I want to achieve is to silently delete a record from a database after the same was created throughout UI. In htat way I want to keep our test environment clear as much as possible and reduce the noise of test data.
After my tests create a new record by clicking over the UI, I wait for POST request to finish and then I would like to extract the id from the response (so I can reuse it to silently delete that record by calling the cy.request('DELETE', '/id')).
Here's a sample test I have put on as a showcase. I'm wondering why nothing is logged in this example.
it('GET cypress and log', () => {
cy.server()
.route('**/repos/cypress-io/cypress*')
.as('getSiteInfo');
cy.visit('https://www.cypress.io/dashboard');
cy.get('img[alt="Cypress.io"]')
.click()
.wait('#getSiteInfo')
.then((response) => {
cy.log(response.body)
})
})
As far as I can see from here https://docs.cypress.io/api/commands/wait.html#Alias this should be fine.
your code contains two problems.
First:
The click triggers a new page to be loaded but cypress does not wait until the PageLoad event is raised (because you do not use visit). On my PC the Request takes about 5 seconds until it is triggered after the click. So you should use wait(..., { timeout: 10000 }).
Second:
wait() yields the XHR object, not the response. So your code within then is not correct. Also the body is passed as object. So you should use JSON.stringify() to see the result in the command log.
This code works:
describe("asda", () => {
it('GET cypress and log', () => {
cy.server()
.route('**/repos/cypress-io/cypress*')
.as('getSiteInfo');
cy.visit('https://www.cypress.io/dashboard');
cy
.get('img[alt="Cypress.io"]')
.click()
.wait('#getSiteInfo', { timeout: 20000 })
.then((xhr) => {
cy.log(JSON.stringify(xhr.response.body))
})
})
})
Instead of route and server method, try intercept directly
I have an app that takes updates into VUEX store and syncs those change from pouchdb to couchdb. Which is great but now I need to have two clients connected and see the change in near realtime.
So I have the https://pouchdb.com/guides/changes.html API which I can use to listen for changes to the DB and when that happens call a action which mutates the vuex state on Client 2. Code below.
However the bit I cannot seem to work out is this code is not just listening all the time ? So where should I put this in Vue to ensure that it hears any changes. I can call it when I make a state change and I see that it hears the change but ofcourse I want to trigger a state change on client 2, without them having to make change. Do I need a timer ? The pouch docs seem to suggest this changes api should be able to update UI based on a change to the data, which I can probably call with a button press to check for changes ...but I want to listen in near realtime ?
pouchdb
.changes({
since: 'now',
include_docs: true
})
.on('change', function(change) {
// received a change
store.commit('CHANGE_STATE', change.doc.flavour)
})
.on('error', function(err) {
// handle errors
console.log(err)
})
Your explanation is a bit fuzzy in that you talk about client 2 without ever mentioning client 1. I assume client 2 is a passive listener and client 1 is where data is changed. If I remember correctly from when I was building my Vue / PouchDB project last year I looked into how to coordinate the Store and the Database, and then thought, "Why bother? They're just two kinds of local storage". As long as changes in client 1 replicate to your Couch server and client 2 detects those server side changes and writes them into reactive variables, they'll propagate to the UI.
I used replicate.to() for storing client-side changes and replicate.from() to detect server-side changes. The replicate() functions have their own timer, constantly monitoring the changes queue, so you don't need to roll your own.
This is what I ended up doing !
actions: {
SYNC_DB() {
// do one way, one-off sync from the server until completion
pouchdb.replicate.from(remote).on('complete', function(info) {
// then two-way, continuous, retriable sync
pouchdb
.sync(remote, { live: true, retry: true })
.on('change', function(info) {
store.commit('CHANGE_STATE', info.change.docs[0].flavour)
})
.on('paused', function(err) {
// replication paused (e.g. replication up to date, user went offline)
})
.on('active', function() {
// replicate resumed (e.g. new changes replicating, user went back online)
})
.on('denied', function(err) {
// a document failed to replicate (e.g. due to permissions)
})
.on('complete', function(info) {
// handle complete
})
.on('error', function(err) {
// handle error
})
})
},
I was wondering if what I've been doing in my ReactNative/Redux application is wrong. This is how I've been handling async actions.
MyComponent.js
componentDidMount() {
fetch('https://www.mywebsite.com')
.then(data => this.props.handleApiSuccess(data)) // injected as props by Redux
.catch(err => this.props.handleApiError(err)); // injected as props by Redux
}
The redux-thunk way I should probably be doing
export const handleApiCall = () => dispatch => {
fetch('https://www.mywebsite.com')
.then(data => dispatch(handleApiSuccess(data)))
.catch(err => dispatch(handleApiError(err)));
}
Is there anything wrong with the way its being done in the first part?
There is nothing wrong in terms of bugs: the code will work and serve its purpose.
But in terms of design it has huge flaw: coupling. Merging your fetching logic inside the Components may cause complications as your app will grow.
What if your way of fetching will change, e.g. you'll decide to communicate with server via websockets? What if your way of handling of server response will change, i.e. handleApiError will have to be replaced with something else? What if you'll decide to reuse same fetching in the different part of your app?
In all these cases you'll have to alter your existing Components which ideally shouldn't be affected by such logic changes.