So basicly we have an initial fetch in our custom pages/_app.jsx that first fetches sitesettings & navigation for header/footer. This data I would like to be only fetched once however it gets fetched every routechange clientside. Is there anyway to persist some data after the initial fetch in the app container?
Here's my code:
import React from 'react'
import App, { Container } from 'next/app'
import Header from '../components/Header';
import Footer from '../components/Footer';
class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {}
const res = await fetch(`http://localhost:3000/navigation`)
const nav = await res.json();
const ss = await fetch(`http://localhost:3000/site-settings`);
const settings = await ss.json();
var culture = "en-us";
var root = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
if (pageProps && pageProps.pageContext) {
culture = pageProps.pageContext.culture || "en-us";
root = nav.message.find(nav => !nav.parentPage && nav.culture === culture);
}
}
return {
pageProps,
navigation: nav.message,
settings,
culture,
root
}
}
And the issue is that the getInitialProps of my _app.jsx is being run at every route making unecessary requests to fetch data that client already have.
There are three separate issues here: first, performing the fetch in _app will guarantee execution for every page, since it is used to initialize each page. That is not what you want. Instead this should happen in the appropriate page.
Second, this shouldn't happen in getInitialProps as that delays the loading of the page. If that is intended, go ahead and do it - but it would be better practice to render the page ASAP, and fill in the gaps later, rather than showing a blank screen.
Third, and most important, you need to load the information you need and manage it in some sort of application state that is shared between all pages. That can be done in redux, React Context, or your own solution for storing the received information if the other solutions feel like overkill for your project. That way you can check if you have it before fetching, and only fetching once.
Related
Below I am pulling all the data from the database. But let's say I deleted one piece of data. How can I retrieve the renewed data? How can I run it again?
export async function getServerSideProps() {
const res = await fetch(`http://localhost:8000/api/getAllShipmentTypes`);
const shipmentTypes = await res.json();
return {
props: { shipmentTypes } // will be passed to the page component as props
};
}
But let's say I deleted one piece of data. How can I retrieve the renewed data?
I think you will need to define what is the trigger for the deletion, I can think of these two.
Another action user performs on a page.
Some other system modifying the database that this client application shows.
For #1, To the action, say a button click you can use a router object to set the same route again which will run getServerSideProps again
When you request this page on client-side page transitions through next/link or next/router, Next.js sends an API request to the server, which runs getServerSideProps
For #2 - this would be handled by giving the user an option to refetch the data from the server again using a link or router component
You can do something like:
import { useRouter } from 'next/router';
function SomePage(props) {
const router = useRouter();
// Call this function whenever you want to
// refresh props!
const refreshData = () => {
router.replace(router.asPath);
}
}
I am building an application with storefront, which uses nextJS. I am able to use getServerSide props while loading a new page.
The page contains many components, each needing their own data. At the moment, I am getting all of these into a results array and then returning from getServerSideProps, as shown below.
export async function getServerSideProps({query}) {
let sid = query.shop
let promises = []
promises.push(getShopCategories(sid))
promises.push(getShopInfo(sid))
promises.push(offersFromShop(sid))
try {
let allPromises = Promise.all(promises)
let results = await allPromises;
//console.log("Shop Info:", results[1])
return {props: {
id: sid,
shopCategories: results[0],
shopInfo: results[1],
offers4u: results[2].products
}}
} catch(e) {
console.error("Failure:", e)
return { props: {}}
}
}
But in this way, I have to get the data needed for all components in one shot. I was thinking, how to let each sub component in the page to have its own 'getServerSideProps'.
I can implement this in each component, but I am unsure about passing the parameters needed (such as shopId, productId etc., which I would have fetched in the main page).
One way is to use cookies, so that the server side can pick up these values. Is there a better solution?
getServerSideProps is only available on direct component under page folder
If you want to fetch more data on sub-component in the page, consider using the useEffect hook or componentDidMount for that work.
I want to use the same application for different customers, where there's a different database for each (which could be on-premise).
As a result, I have no data at the build phase (e.g. in CI/CD) that I could use to create static sites.
I thought about skipping generating the sites in getStaticProps via an environment variable.
When building the sites, I could tell Next.js to not use any data, something like this:
export const getStaticProps: GetStaticProps<HomePageProps> = async () => {
const isBuildPhase = process.env.IS_BUILD;
const data = isBuildPhase ? null : await fetchData();
return {
props: {
data: data ?? null,
},
revalidate: 5 * 60,
};
};
Now, I want to create the sites only at runtime (with next start), because at runtime, the built application has access to its database. In each getStaticProps the environment variable will be configured so data is fetched. When the application starts initially, it will generate all static sites when they're accessed.
Are there big downsides with this approach?
Are there maybe better solutions to this problem?
We had a similar requirement where the app needed to serve multiple tenants pages, but each tenant data is different. Which meant the app did not have access to data at build time and only runtime.
We leveraged getStaticPaths and getStaticProps to do this.
getStaticPaths
This method returns a fallback option (true || false || blocking), which we can use to decide to show a loader on the UX or block until the actual page loads.
export async function getStaticPaths() {
// Return empty paths because we don't want to generate anything on build
// { fallback: blocking } will server-render pages
// on-demand if the path doesn't exist.
return {
paths: [],
fallback: 'blocking',
};
}
When using this method, there isn't a need to maintain IS_BUILD env variable. (Depending on your specific use-case you may choose to use it or not)
getStaticProps
This method does the actual data fetching based on the URL path params for a tenant.
export async function getStaticProps({ params }) {
// Run your data fetching code here
const data = await fetch(params);
return {
props: data,
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10, // In seconds
notFound: !data,
};
}
We also leverage Incremental Static Regeneration, to make sure that we refresh the page every revalidate seconds.
Pages
Single Template Tenants
When all the tenants share the same components, it's pretty straight forward:
const SingleTenantPage = ({ data }) => {
return <Component {...data} />;
};
export default SingleTenantPage;
Multi-Template Tenants
The actual page, just parses the props (passed down from getStaticProps), and then loads the appropriate component for that page.
This way we leverage a single route for multiple tenants. example.com/app/tenantA, example.com/app/tenantB, example.com/app/tenantC all 3 routes can be served out of pages/app/[slug]/index.js.
Using dynamic imports, we make sure that only the component for a specific tenant is loaded. (also helps in code splitting)
// Dynamic Import so we load only the required bundles
const templates = {
tenantA: dynamic(() => import(`../templates/tenantA`)),
tenantB: dynamic(() => import(`../templates/tenantB`)),
tenantC: dynamic(() => import(`../templates/tenantC`)),
};
const MultiTenantPage = ({ data }) => {
// Provided template is present in the data
// template: 'tenantA' || 'tenantB' || 'tenantC'
const { template, ...rest } = data || {};
// If the template doesn't exist, show a 404 Page instead
const Component = templates[template] || (() => <Error statusCode="404" />);
return <Component {...rest} />;
};
export default MultiTenantPage;
The multi-tenant page works well for us. We use a larger revalidate value because data isn't changing that often. Only caveat we had were a little bit complex test cases because of all the dynamic imports.
The above solution is very much similar to what you've considered for your use-case, albeit without an additional env variable (IS_BUILD)
I have a menu component that appears globally. What is the best practice for getting data into that component?
I'm trying to take advantage of static generation that Next.js offers but all data fetching guidance from the Next.js team relates to pages. getStaticProps and getStaticPaths seem to pertain to page generation, not data for components. Is their SWR package the right answer, or Apollo Client?
Typically in hooks-based React, I'd just put my data call into useEffect. I'm not sure how to reason this out being that everything is rendered at build time with Next.
This is such a tricky problem, I think we need to lay out some background before a solution comes into focus. I'm focusing in the React.js world but a lot of this would apply to Vue/Nuxt I'd imagine.
Background / Static Generation Benefits:
Gatsby and Next are focused on generating static pages, which vastly improves performance and SEO in React.js sites. There is a lot of technical overhead to both platforms beyond this simple insight but let's start with this idea of a digital machine pumping out fancy HTML pages for the browser.
Data Fetching for Pages
In the case of Next.js (as of v9.5), their data fetching mechanism getStaticProps does most of the heavy lifting for you but it's sandboxed to the /pages/ directory. The idea is that it does the data fetching for you and tells the Next.js page generator in Node about it during build time (instead of doing it component-side in a useEffect hook - or componentDidMount). Gatsby does much the same with their gatsby-node.js file, which orchestrates the data fetching for page building in concert with a Node server.
What about Global Components that need data?
You can use both Gatsby and Next to produce any kind of website but a huge use case are CMS-driven websites, because so much of that content is static. These tools are an ideal fit to that use case.
In typical CMS sites, you will have elements that are global - header, footer, search, menu, etc. This is where static generation faces a big challenge: how do I get data into dynamic global components at build time? The answer to this question is... you don't. And if you think about this for a minute it makes sense. If you had a 10K page site, would you want to trigger a site-wide rebuild if someone adds a new nav item to a menu?
Data Fetching for Global Components
So how do we get around this? The best answer I have is apollo-client and to do the fetch client side. This helps us for a number of reasons:
For small size queries, the performance impact is negligible.
If we need to rebuild pages for changes at the CMS layer, this slides by Next/Gatsby's detection mechanisms, so we can make global changes without triggering gigantic site-wide rebuilds.
So what does this actually look like? At the component level, it looks just like a regular Apollo-enhanced component would. I usually use styled-components but I tried to strip that out so you can could better see what's going on.
import React from 'react'
import { useQuery, gql } from '#apollo/client'
import close from '../public/close.svg'
/**
* <NavMenu>
*
* Just a typical menu you might see on a CMS-driven site. It takes in a couple of props to move state around.
*
* #param { boolean } menuState - lifted state true/false toggle for menu opening/closing
* #param { function } handleMenu - lifted state changer for menuState, handles click event
*/
const NAV_MENU_DATA = gql`
query NavMenu($uid: String!, $lang: String!) {
nav_menu(uid: $uid, lang: $lang) {
main_menu_items {
item {
... on Landing_page {
title
_linkType
_meta {
uid
id
}
}
}
}
}
}
`
const NavMenu = ({ menuState, handleMenu }) => {
// Query for nav menu from Apollo, this is where you pass in your GraphQL variables
const { loading, error, data } = useQuery(NAV_MENU_DATA, {
variables: {
"uid": "nav-menu",
"lang": "en-us"
}
})
if (loading) return `<p>Loading...</p>`;
if (error) return `Error! ${error}`;
// Destructuring the data object
const { nav_menu: { main_menu_items } } = data
// `menuState` checks just make sure out menu was turned on
if (data) return(
<>
<section menuState={ menuState }>
<div>
{ menuState === true && (
<div>Explore</div>
)}
<div onClick={ handleMenu }>
{ menuState === true && (
<svg src={ close } />
)}
</div>
</div>
{ menuState === true && (
<ul>
{ data.map( (item) => {
return (
<li link={ item }>
{ item.title }
</li>
)
})}
</ul>
)}
</section>
</>
)
}
export default NavMenu
Set Up for Next to Use Apollo
This is actually really well documented by the Next.js team, which makes me feel like I'm not totally hacking the way this tool is supposed to work. You can find great examples of using Apollo in their repo.
Steps to get Apollo into a Next app:
Make a custom useApollo hook that sets up the connection to your data source (I put mine in /lib/apollo/apolloClient.js within Next's hierarchy but I'm sure it could go elsewhere).
import { useMemo } from 'react'
import { ApolloClient, InMemoryCache, SchemaLink, HttpLink } from '#apollo/client'
let apolloClient
// This is mostly from next.js official repo on how best to integrate Next and Apollo
function createIsomorphLink() {
// only if you need to do auth
if (typeof window === 'undefined') {
// return new SchemaLink({ schema })
return null
}
// This sets up the connection to your endpoint, will vary widely.
else {
return new HttpLink({
uri: `https://yourendpoint.io/graphql`
})
}
}
// Function that leverages ApolloClient setup, you could just use this and skip the above function if you aren't doing any authenticated routes
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(),
cache: new InMemoryCache(),
})
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract()
// Restore the cache using the data passed from getStaticProps/getServerSideProps
// combined with the existing cached data
_apolloClient.cache.restore({ ...existingCache, ...initialState })
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient
return _apolloClient
}
// This is goal, now we have a custom hook we can use to set up Apollo across our app. Make sure to export this!
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}
Modify _app.js in the /pages/ directory of Next. This is basically the wrapper that goes around every page in Next. We're going to add the Apollo provider to this, and now we can globally access Apollo from any component.
import { ApolloProvider } from '#apollo/react-hooks'
import { useApollo } from '../lib/apollo/apolloClient'
/**
* <MyApp>
*
* This is an override of the default _app.js setup Next.js uses
*
* <ApolloProvider> gives components global access to GraphQL data fetched in the components (like menus)
*
*/
const MyApp = ({ Component, pageProps }) => {
// Instantiates Apollo client, reads Next.js props and initialized Apollo with them - this caches data into Apollo.
const apolloClient = useApollo(pageProps.initialApolloState)
return (
<ApolloProvider client={ apolloClient }>
<Component {...pageProps} />
</ApolloProvider>
)
}
export default MyApp
And now you can get dynamic data inside of your components using Apollo! So easy right ;) HA!
For global data fetching in NextJS, I use react-query and there is no need for a global state because it lets you to cache the data. Let's say you have a blog with categories and you want to put the category names in the navbar as a dropdown menu. In this case you can call the API to fetch the data with react-query from the navbar component and cache it. The navbar data will be available for all pages.
I'm using next.js and apollo with react hooks.
For one page, I am server-side rendering the first X "posts" like so:
// pages/topic.js
const Page = ({ posts }) => <TopicPage posts={posts} />;
Page.getInitialProps = async (context) => {
const { apolloClient } = context;
const posts = await apolloClient.query(whatever);
return { posts };
};
export default Page;
And then in the component I want to use the useQuery hook:
// components/TopicPage.js
import { useQuery } from '#apollo/react-hooks';
export default ({ posts }) => {
const { loading, error, data, fetchMore } = useQuery(whatever);
// go on to render posts and/or data, and i have a button that does fetchMore
};
Note that the useQuery here executes essentially the same query as the one I did server-side to get posts for the topic.
The problem here is that in the component, I already have the first batch of posts passed in from the server, so I don't actually want to fetch that first batch of posts again, but I do still want to support the functionality of a user clicking a button to load more posts.
I considered the option of calling useQuery here so that it starts at the second "page" of posts with its query, but I don't actually want that. I want the topic page to be fully loaded with the posts that I want (i.e. the posts that come from the server) as soon as the page loads.
Is it possible to make useQuery work in this situation? Or do I need to eschew it for some custom logic around manual query calls to the apollo client (from useApolloClient)?
Turns out this was just a misunderstanding on my part of how server side rendering with nextjs works. It does a full render of the React tree before sending the resulting html to the client. Thus, there is no need to do the "first" useQuery call in getInitialProps or anything of the sort. It can just be used in the component alone and everything will work fine as long as getDataFromTree is being utilized properly in the server side configuration.