While reading the Next.Js tutorial in the Routing API I learned about fetching data with these 2 libs.
The fetch object from Isomorphic-unfetch, is used within the getInitialProps async function to call an external API. Then in the Route API part, the SWR along with the { useRouter } from 'next/router; shapes the call to an internal API developed within the same Next.Js server with a lot of flexibility to query the req params.
Other than these 2 aspects, what other differences are between these 2 approaches?
isomorphic-unfetch allows you to make fetch calls on both the client and the server, which is why it's shown in examples that use getInitialProps.
Generally speaking, you fetch data on the server using getInitialProps. This will be blocking – meaning the markup will not be returned until your data has been fetched. Consider a product page for an e-commerce site. It's important that we return the product name, price, and other information from the server and not on the client-side.
SWR is similar, but a bit different. It first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again. A real-world example of where you'd use something like SWR is on a dashboard page. You don't want to fetch all the data in getInitialProps in a blocking manner, so you render out the dashboard "shell" in a loading state, and then use SWR to fetch the data client side. You can view an example of this here.
Source - Creator of Mastering Next.js 😄
Related
I'm new in Next.js and GraphQL world. So far i've been using react with reduxjs and axios for API calls. I would learn more advanced stuff so here is my question. If i'm using apollo graphql what options do i have for local state management? It can be handled by apollo itself or i should use external tool like redux store?
Apollo at its heart is a GraphQL implementation that helps people manage their data. They also make and maintain a GraphQL client (Apollo Client) which we can use with React frameworks like Next.js.
The Apollo Client is a state management client that allows you to manage both local and remote data with GraphQL and you can use it to fetch, cache, and modify application data.
In this article, we’ll discuss why we should use the Apollo Client with Next.js and how we can use the Apollo Client with Next.js to render pages via the three rendering methods Next.js supports; static site generation (SSG), server-side rendering (SSR), and client-side rendering (CSR).
If you want to use your Redux and Apollo state in a component, you need to use both graphql from react-apollo and connect from react-redux. This will let you better track the different events that happen in your app, and how your client and server side data changes interleave.
Why use Apollo Client with Next.js
First, let’s look at why we should use the Apollo Client with Next.js. There are three key reasons to use the Apollo Client:
Out-of-the-box support for caching
Built-in loading and error states
Declarative approach to data fetching
Out-of-the-box support for caching
In Apollo’s own words, “Caching a graph is no easy task, but we’ve spent two years focused on solving it.”
Apollo has invested serious amounts of time in making their caching process the most efficient and effective they can. So, why try and reinvent the wheel? If you’re fetching data in your application and working with GraphQL, then the Apollo Client is a great way of handling your data.
Another benefit is that there is minimal setup required for developers using the client. Apollo even labels it as “zero-config.” We will see this in our application example further in the post, but to set up caching in an application, all we need to do is add the code below to our application:
import { ApolloClient, InMemoryCache } from '#apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache()
})
Built-in loading and error states
The Apollo Client has a custom React Hook built into it called block useQuery, which we will use in our example application, and gives us built-in loading and error states for us to use.
While this doesn’t sound impressive, what it means for developers is that we don’t need to spend time implementing this logic ourselves, we can just take the booleans the Hook returns and change our application rendering as required.
Thanks to these built-in states, using the Apollo Client means we can spend less time worrying about implementing data fetching logic and focus on building our application.
Declarative approach to data fetching
Another benefit of the way the Apollo Client implements the useQuery Hook is that data fetching with the Apollo Client is declarative rather than imperative.
What this means for us is we only need to tell Apollo what data we want and it gets it for us. We don’t need to write the logic and give it a list of step-by-step instructions on how to do it or handle it.
Once again, this is another great example of how the Apollo Client helps speed up development and make us more efficient developers when working with GraphQL.
You can learn more in this page right here if why use nextjs with apollo: This link
By default, Apollo Client creates its own internal Redux store to manage queries and their results. If you are already using Redux for the rest of your app, you can have the client integrate with your existing store instead.
In simple words, When you're using Apollo, you shouldn't be putting that data into Redux. You can still use Redux for other things, but apollo's duty is to store that data and make it accessible to your components. Taking it out and putting it into Redux means doing double the work for no added gain, and there's a strong risk you'll introduce a lot of asynchrony between the two levels as a result.
Referenced from here:
enter link description here
And learn more if u want to integrate redux and apollo from here: enter link description here
Learn more if it is necessary to use redux with apollo right here as well: enter link description here
I need to pull data from an external third-party API, and the request to the API has to come from the server-side rather than the client-side (the API will reject client-side requests).
I'm looking to use getServerSideProps, since according to the NextJS API it " only runs on server-side and never runs on the browser" which is exactly what I need.
However, once I pull the data from the API, I won't need to re-pull the data for another 15-30 minutes. During that time, I would use the previous response.
For this, swr sounds good, since it can be made into a reusable hook and "there will be only 1 request sent to the API, because they use the same SWR key and the request is deduped, cached and shared automatically."
The page's flow would look like:
User navigates to page and requests data
If the data does not already exist from a prior pull, use getServerSideProps to pull and store the data
If the data does exist and was pulled within the last 30 minutes, use swr (or some other method) to call an internal API and process the existing data, thereby avoiding another external API request.
The problem with this is getServerSideProps "must be exported as a standalone function — it will not work if you add getServerSideProps as a property of the page component", and it will run every time the page is requested.
Is there a way I can use getServerSideProps but only run it conditionally? Or is there another way that is more appropriate for this situation?
use getStaticProps which only runs during build-time. HTML will be created and will be placed into cache. when first request comes, html will be served from the cache
export async function getStaticProps(context) {
const data = await fetchData(args);
return {
props: {
// make sure you do not return undefined. it does not get serialized
myProp: data,
},
// first request will be returned from cache
// then data will be revalidated and cache will be updated
revalidate: 10*60, // In seconds. 10 minutes
};
}
I have data on a flask backend that I would like to fetch and display on my react frontend. By using hooks data will be fetched everytime the page is requested. What I would like to do is to fetch data only once at the beginning (if it is not already fetched) and then I can adapt it to each frontend page without having to fetch the data everytime a filter on my page changes.
Is there a standard way to solve this problem? Do I have to use redux to persist state on the frontend or is there an easier way?
I want to share state fetched from the backend between components, just like I would using redux. Specifically, once a user is logging in, the response he gets includes settings, notifications and recent posts. How do I distribute those across components using urql? I want to avoid fetching all this data in separate requests
From what I've found on github urql has no local state (like apollo has apollo-link-state), but only cache.
You could either cache the data or:
use React Context
store the data in localstorage
I'm currently building my first next app (e-commerce with Shopify Storefront API).
In order to avoid multiple query to the db and upgrade performance, I want to store all datas once a user sees a page:
1- first loading (by page): the method getStaticProps fetch the necessary datas and put everything in a context ShopContext
2- when the user hits the page another time: instead of getStaticProps re-fetch the datas, just use the data in the context.
Is it something logical to do that? And if yes, is it possible to avoid data fetching when a loading page occurs?
Many thanks for your responses ! :)