How is this fetch optimised on react gatsby website - javascript

On the front page of a website served with a Gatsby React setup I have a NavbarExtra component that shows some data via an api. The data coming from that endpoint changes several times a day.
The idea now is now to optimize the fetch so the fetch is made as seldom as possible so the api is used as rearly as possible, it has a limit to it(different paid plans).
The scenario should be that as long as the user has entered the site the fetch will only happen at once. Then the user can go around the site maybe close even the component with the fetch and again go back to the front-page where the fetch is made.
Now the component is called in the navmenu if the user is only on the front page:
{isLandingPage && <NavBarData/>} and in that component there is this fetch:
useEffect(() => {
fetch(
'https://endpoint',
{
method: 'GET',
headers: {
},
}
)
.then(response => {
if (response.status >= 200 && response.status <= 299) {
return response.json();
}
throw Error(response.statusText);
})
.then(data => {
const { result } = data.quoteResponse;
setNumbers(result));
})
.catch(error => {
console.log(error);
});
}, 0);
Firstly I would like to ask for how should this fetch be done so the api is used as rearly as possible, so the user gets the recent data and only gets it again when for example reloading the page?
Secondly I understand some concepts about single page apps and static site generators as here the used Gatsby, and probably have understood it right that if I would like to use the fetched data on different pages(even other pages than the isLandingPage) of the website I could just use it in one component that is served on different pages and it would not refetch on each page enter?

You could create a Parent component that fetches the data and can retrieve the data to the childrens, so you only control the fetch in one component only one time on each session, or wherever you need it. In this case depending on you architechture you could use simple stateor the context API to reuse this data on several and nested components.
Other solution could involve using the localStorage, so you could store the data fetched on the localStorage and reuse this data on any component, you just will have to update the data when you need it.

Related

Next.js + Strapi blog: content not updated

I have a Next.js app in production. My content is managed via Strapi. I fetch all the content with getStaticProps function on each page (2 pages actually, small blog).
However, when I create new content or update an existing one, my Next.js app doesn't fetch the new or updated content.
Maybe due to the fetching at build time? If yes, can I have the possibility to fetch the content on client side and have the benefit of SEO?
Any idea?
Many thanks! :)
Considered setting up a revalidate policy for Incremental Static Regeneration to freshen-up stale content.
https://nextjs.org/docs/basic-features/data-fetching#incremental-static-regeneration
// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// revalidation is enabled and a new request comes in
export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10, // In seconds
}
}
If that doesn't fit your update policy, you'll have to move to server-side rendering and fetch data on each request.

React Native: How can i fetch Data instant before rendering Screen?

I tried it with this method
useEffect(() => {
async function getUserData() {
var userData = await firebase.firestore().doc("ingredients/" + user.uid).get();
var labels = []
userData.data().ingredients.forEach(ingredient => {
labels.push(ingredient.label)
})
setUserIngredients(labels)
setUserRecipes(userData.data().recipes)
}
getUserData()
fetchRecipes(userIngredients)
}, [])
but it does not load when I use the app I need to save the file on my computer before it fetches the data. I'm using expo to debug the app on my smartphone. I want it to fetch the data when I go to the screen or when my app is starting
You can use loader when data is being fetching and hide it when data is fetched !
also if you want instant data fetch even before rendering screen ,then it is not the good approach if you really want it then do data fetch in custom constructor!
i.e
const [constructorHasRun, setConstructorHasRun] = useState(false);
and call fetch API in this constructor
const constructor = () => {
if (constructorHasRun) return;
// fetch API
setConstructorHasRun(true);
};
Hope You wants it and helped !
For these cases, I recommend saving data in Redux states is helping your app seems fast and you can access it when you need it.
Also, if you don't use Redux, you can save your data in SQLite because it seems your data about recipes, and update your data in the splash screen.
That's just another solution...

Data VS Async Data in Nuxt

Im using vue.js with nuxt.js, I'm just still confused as when to use Data VS Async Data. Why would I need to use Async data when I just have data that just displays on the page?
I have a data object of FAQ's and just want to display the data without doing anything with it. What are the benefits of using the asyncData? Or what are the cases or best use of them?
Should I display list data such as this as async by default if using data such as this inside of my component?
Data
data:() => ({
faqs:[
{"title":"faq1"},
{"title":"faq2"},
{"title":"faq3"},
]
}),
asyncData
asyncData(context) {
return new Promise((resolve, reject) => {
resolve({
colocationFaqs:[
{"title":"faq1"},
{"title":"faq2"},
{"title":"faq3"},
]
});
})
.then(data => {
return data
})
.catch(e => {
context.error(e);
});
},
asyncData happes on the serer-side. You cant access browser things like localStorage or fetch() for example but on the ther hand you can access server-side things.
So why should you use asyncData instead of vue cycles like created?
The benefit to use asyncData is SEO and speed. There is this special context argument. It contains things like your store with context.store. Its special because asyncData happens on server-side but the store is on the client side usually. That means you can get some data and then populate your store with it and somewhere else you display it. The benefit of this is that its all server-side and that increase your SEO so for example the google crawler doesnt see a blank page
why would I need to pre render it when it is going to be displayed
anyway
Yes for us it doesnt matter if i send 1 File to the client and it renders all data like in SPA's or if its pre-rendered. But it doesnt matter for the google crawler. If you use SPA mode the crawler just sees a blank page. You can discoverd it too. Go to any SPA website and click right-click and inspect you will see thats there only 1 Div tag and few <script> tags. (Dont press F12 and inspect like this thats not what i mean).

Update an element automatically in a website using NodeJs

I am still in early stages of my programming and I was thinking about creating something which does API calls after every x seconds and update my website with new content.
My intial goal is to populate a table with the content obtained from API using FOR loop (.ejs page).
Now, I want to update just those rows and columns (created from FOR loop) of my webpage after x seconds instead of refreshing my entire page.
How can I achieve this (Updating those rows and columns) ?
Consider stock market website, where it just updates the stock price, instead of entire page.
Thanks for your help in advance
The most popular way to solve this problem is to store the data you obtain from the other API in your database, then create an endpoint that serves the most recent version of that data as JSON.
Then at the client side, you make periodic requests to the server to fetch the content and updates a part of the page to show the newest data available.
This could be as simple as:
// server side (if you use express)
app.get("/data", (req, res) => {
database.getMostRecentEntry()
.then(data => res.json(data))
.catch(err => res.status(500).end());
});
// client side
function fetchMostRecentData() {
fetch("/data")
.then(response => response.json())
.then(data => updateView(data))
.catch(err => showError(err));
}
function updateView(data) {
let container = document.getElementById("app");
container.innerHTML = `
<tr>
<td>${data.name}</td>
<td>${data.value}</td>
</tr>
`;
}
function showError(err) {
console.error(err);
alert("Something went wrong");
}
// call fetchMostRecentData once every 10s
setInterval(fetchMostRecentData, 10000);
Now, this isn't a very robust solution and there are some fairly serious security problems, but it's a starting point.
From here, you should look into using a frontend framework (rather than updating innerHTML yourself). You could also look at using websockets, rather than serving the data through a HTTP endpoint.
I'd look into using expressjs in combination with node.js to build your website. Then using ajax inside your html to accomplish the rest api call updates.

Trying to hit an API with JSON data in REACT

I have just started learning to code in ReactJS and have come to the part where I need to hit an API to get back JSON data.
I am running this on a node server on my local which tries to build it each time I make a change - this helps because it shows me where my errors are. Unfortunately it doesn't mean I know why I am getting an error.
This is my code so far:
import React from 'react';
import './App.css';
var GetUnassignedClients = React.createClass({
unassignedClients: function () {
return $.getJSON('http://localhost/backoffice/?action=unassignedClients.getUnassingedClients')
.then((data) => {
this.setState({resultMe: data.results});
});
},
render: function() {
return (
<div>this.state.resultMe</div>
);
}
});
module.exports = GetUnassignedClients;
I will re-paste the bit that seems to be throwing the error:
return $.getJSON('http://localhost/backoffice/?action=unassignedClients.getUnassingedClients')
.then((data) => {
this.setState({resultMe: data.results});
});
The error seems to be pointing at the $ - when I wrap this all in {} then it points to the full stop (.).
Not sure if I am doing something wrong or missing something.
The $in the $.getJSON is referring to jQuery. Do you have it included in your page? Javascript is trying to parse the dollar sign and can't find it. Other possible solution is to use a separate http library (if you don't need jQuery), such as axiois or fetch for example.
Im not sure, but I thought you would hit in this way
fetch(`http://localhost:8088/api/this/is/an/api/call`)
.then(result=> {
this.setState({items:result.json()});
});
Okay turns out I was trying to use $.getJSON which is JQuery - due to building this on my local using a node server JQuery wasn't included on my local development before the production code was built.
So instead I looked into using fetch that seems to be the go to when coding in react.
I also moved this section into a componentDidMount function so the app would be loaded and then the API call would be made - not that I have a lot of data to load but it's good practice for when you do.
My working code for this section:
componentDidMount () {
fetch("http://localhost/dashboard/?action=unassignedUsers.getUnassingedUsers", {
credentials: 'same-origin'
})
.then(response => response.json())
.then(json => this.setState({data: json}));
}
I also came across a couple issues using fetch - if you need a session available to access said data then you need to specifically pass through the credentials or the API call will re-direct to the login page. At first I saw a status 200 but no data - as it successfully re-directed to the login page, but obviously there was no JSON to access here.

Categories

Resources