NextJS dynamically rendered components via SSR losing reactivity - next.js

I'm trying to use a Contentful references field to generate SSR landing pages which are populated with dynamic React components mapped to each content type.
The references field is basically an array of other content types that the user can add / edit / remove / reorder as they see fit:
The Contentful API is called in getServerSideProps.
export async function getServerSideProps(context) {
const config = require('../../config');
const contentful = require('contentful');
const client = contentful.createClient({
space: config.contentful.spaceId,
accessToken: config.contentful.deliveryAccessToken,
environment: config.contentful.environment,
});
const content = await client.getEntries({
content_type: 'landingPage',
'fields.slug': context.query.slug,
include: 2,
});
return { props: { landingPage: content.items[0]}};
};
The components are then rendered dynamically like so:
const LandingPage = (props) => {
return (
<MainLayout>
<div>{renderComponents(props.landingPage.fields.body)}</div>
</MainLayout>
);
};
renderComponents: (componentMap is just an object mapping item.sys.contentType.sys.id strings to React components)
const renderComponents = (data) => {
return data
.filter((item) => {
return item.sys.contentType.sys.id in componentMap;
})
.map((item, index) => {
const Component = componentMap[item.sys.contentType.sys.id];
const props = item.fields;
return (
<Component {...props} />
);
})
};
This all seems to works fine in both dev and production builds, however I've noticed that if I create another non-SSR page that uses these same components, all interactivity is lost from the SSR pages only.
This happens for all components on the dynamic page, even the ones that were not generated by the renderComponents function (for example, the navigation, which is standard across the entire site, and is part of MainLayout).
Deleting the non-dynamic pages immediately causes the interactivity return.
There are no error messages in either the browser console or terminal, which is making it difficult to debug exactly what is going wrong here.
Any advice appreciated,
Thanks
next.config.js is unchaged from default:
module.exports = {
useFileSystemPublicRoutes: true,
};

Related

React Query - useQuery callback dependent on route parameter? [duplicate]

When page is refreshed query is lost, disappears from react-query-devtools.
Before Next.js, I was using a react and react-router where I would pull a parameter from the router like this:
const { id } = useParams();
It worked then. With the help of the, Next.js Routing documentation
I have replaced useParams with:
import { usePZDetailData } from "../../hooks/usePZData";
import { useRouter } from "next/router";
const PZDetail = () => {
const router = useRouter();
const { id } = router.query;
const { } = usePZDetailData(id);
return <></>;
};
export default PZDetail;
Does not work on refresh. I found a similar topic, but manually using 'refetch' from react-query in useEffects doesn't seem like a good solution. How to do it then?
Edit
Referring to the comment, I am enclosing the rest of the code, the react-query hook. Together with the one already placed above, it forms a whole.
const fetchPZDetailData = (id) => {
return axiosInstance.get(`documents/pzs/${id}`);
};
export const usePZDetailData = (id) => {
return useQuery(["pzs", id], () => fetchPZDetailData(id), {});
};
Edit 2
I attach PZList page code with <Link> implementation
import Link from "next/link";
import React from "react";
import TableModel from "../../components/TableModel";
import { usePZSData } from "../../hooks/usePZData";
import { createColumnHelper } from "#tanstack/react-table";
type PZProps = {
id: number;
title: string;
entry_into_storage_date: string;
};
const index = () => {
const { data: PZS, isLoading } = usePZSData();
const columnHelper = createColumnHelper<PZProps>();
const columns = [
columnHelper.accessor("title", {
cell: (info) => (
<span>
<Link
href={`/pzs/${info.row.original.id}`}
>{`Dokument ${info.row.original.id}`}</Link>
</span>
),
header: "Tytuł",
}),
columnHelper.accessor("entry_into_storage_date", {
header: "Data wprowadzenia na stan ",
}),
];
return (
<div>
{isLoading ? (
"loading "
) : (
<TableModel data={PZS?.data} columns={columns} />
)}
</div>
);
};
export default index;
What you're experiencing is due to the Next.js' Automatic Static Optimization.
If getServerSideProps or getInitialProps is present in a page, Next.js
will switch to render the page on-demand, per-request (meaning
Server-Side Rendering).
If the above is not the case, Next.js will statically optimize your
page automatically by prerendering the page to static HTML.
During prerendering, the router's query object will be empty since we
do not have query information to provide during this phase. After
hydration, Next.js will trigger an update to your application to
provide the route parameters in the query object.
Since your page doesn't have getServerSideProps or getInitialProps, Next.js statically optimizes it automatically by prerendering it to static HTML. During this process the query string is an empty object, meaning in the first render router.query.id will be undefined. The query string value is only updated after hydration, triggering another render.
In your case, you can work around this by disabling the query if id is undefined. You can do so by passing the enabled option to the useQuery call.
export const usePZDetailData = (id) => {
return useQuery(["pzs", id], () => fetchPZDetailData(id), {
enabled: id
});
};
This will prevent making the request to the API if id is not defined during first render, and will make the request once its value is known after hydration.

Next.js change url without building the page using ISR

I am using ISR to build static product pages using next.js. Since there are a lot of product page to generate I only generated a few pages for it. The problem that I am trying to solve is the delay in transferring the view to the product page.
So I have a category page and within it have a list of products. On each product card item, I use next.js link so that the user can go to the product page.
The problem here is the delay going to the product page when the page is not yet generated. Going to the product page is slow because next.js is building the page. I want to transfer the user to the product page immediately while showing the loading state of the page via the router.isFallback condition.
What I'm trying to achieve is the same as what a normal link would do because it shows the loading state of the page but I don't want to reload the page.
Instead of using next/link or router.push, use router.replace
router.replace(`/product/${id"}`)
Let me know if this work.
What you could do is to make the props not required,
The thing that must take time during the loading of you're ISG page of nextJs is the call api in GetStaticProps,
Something like that:
export async function getStaticProps({ params }) {
const { status, data } = await axios.get<Data>(
`${server}/data`
);
if (status === 404) {
return { notFound: true };
}
return {
props: {
...data
},
revalidate: 60,
};
}
But you could also decide that you will fetch the data during the loading of the state with a fall-back blocking:
const MyPage = (props) => {
const [data,setData] = useState<Data>(null);
useEffect(() => {
(function()
const {data} = axios.get(`${server}/data`);
setData(data);
)()
},[])
return(
<div>
!data ? <div>loading ... </div> : <div>Product: {data}</div>
</div>
)
}
export async function getStaticProps({ params }){
return {
props: {
isloading: true
},
revalidate: 60,
};
}

At what stage getStaticProps() fetch the data from my API?

I'm trying to understand when exactly does getStaticProps fetch the data.
is it on the build process or every time the website is been render to someone (every time someone visits my app)
if it's the first one, doesn't it make my app "static" meaning it won't update the data when the data on my DB is changed?
Thanks!!
I am going to sleep So I just copied below answer from NextJS Docs
Next.js allows you to create or update static pages after you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, without needing to rebuild the entire site. With ISR, you can retain the benefits of static while scaling to millions of pages.
To use ISR add the revalidate prop to getStaticProps:
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
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
}
}
export async function getStaticPaths() {
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// We'll pre-render only these paths at build time.
// { fallback: blocking } will server-render pages
// on-demand if the path doesn't exist.
return { paths, fallback: 'blocking' }
}

Caching into subcomponents

I'm building a site in nextjs but I came across a problem.
I have the cover of the site, where there is a list of products, and on the top menu the list of product categories.
The products are looking via getStaticProps (So that it is done by the servideor and is cached).
However, the categories are inside a separate component, where inside I need to load the category listing from my API.
getStaticProps does not work in this case as it is not a page but a component.
Fetching inside a useEffect is bad, as each access loads the api.
So the question remains, how can I do this server-side fetch and deliver the cached (json) return? (Simulating getStaticProps)
As your component is listed on every page, you could consider either using Context or local caching in the browser within the shared Category component.
Context provides a way to pass data through the component tree without
having to pass props down manually at every level.
But there are performance considerations using Context and may be overkill here. If you really don't want to hit the API, data is not changing often, and you don't need to pass functions through the component tree, then you could consider some basic browser caching using localStorage.
import React, { useState, useEffect } from 'react';
const mockAPI = () => {
return new Promise((resolve) => {
setTimeout(() => {
return resolve([
{
id: '1',
name: 'One'
},
{
id: '2',
name: 'Two'
}
]);
}, 1000);
});
};
const Component = () => {
const [categories, setCategories] = useState(null);
useEffect(() => {
(async () => {
if (categories === null) {
let data = window.localStorage.getItem('categories');
if (data === null) {
console.info('calling api...');
data = await mockAPI();
window.localStorage.setItem('categories', JSON.stringify(data));
}
setCategories(JSON.parse(data));
}
})();
}, []);
return <nav>{categories && categories.map((category) => <li key={category.id}>{category.name}</li>)}</nav>;
};
export default Component;
The caveat here is you need to know where to clear localStorage. There are many ways to implement this from using basic timers to looking at SWR
You could also consider Redux but is probably overkill for something elementary like this.

Next.js: How to create multiple dynamic pages coming from different types of API?

This is my first experience with Next.js. I am trying to create a dynamic route from the data coming from server.
I do convert the id to string but have the same error.
Server Error
Error: A required parameter (articleid) was not provided as a string in getStaticPaths for /article/[articleid]
I tried something similar with the data from web api it works fine but not for the data that I fetch from server. Can't figure out what I am missing.
Also why error message is pointing out server error in the first line?
Here is the component the error is coming from: pages/article/[articleid]/index.js
export const getStaticProps = async (context) => {
const res = await fetch(`${server}/api/article/${context.params.id}`);
const article = await res.json();
return {
props: {
article,
},
};
};
export const getStaticPaths = async () => {
const res = await fetch(`${server}/api/article/`);
const articles = await res.json();
const ids = articles.map((article) => article.id);
const paths = ids.map((id) => ({ params: { id: id.toString() } }));
return {
fallback: "blocking",
paths: paths,
};
};
`pages/api/article/[id].js file
import { articles } from "../../../data";
export default function handler({ query: { id } }, res) {
const filteredData = articles.filter((article) => article.id === id);
if (filteredData.length > 0) {
res.status(200).json(filteredData[0]);
} else {
res.status(404).json({ message: `article with id of ${id} is not found` });
}
}
UPDATE
I found out that my problem is definitely not from the code provided above.
Actually in my app I have another dynamic page where I fetch the data from another web api, which works fine. Changing the urls I found out that now web api dynamic page is throwing the same error. I assume the problem is that how I defined the paths, , [articleid] I mean.
Here is my components structure
The problem is with `pages/article/[articleid].
Here is how I am linking to the specific item
<Link href="/article/[articleid]" as={`/article/${article.id}`}>
<a className={styles.container}>
<h1>{article.title} →</h1>
<p>{article.body}</p>
</a>
</Link>
Any help will be appreciated
Actually I made it work changing the dynamic route id name in brackets, in my case [articleid], to just [id] and it worked fine. Image below.
But honestly, I didn't understand why the previous keyword ([articleid]) in brackets was not working.
I also tried another keywords inside the brackets for dynamic route like [article] and nothing worked except [id].
I didn't find anything related in Next.js docs about that.
I'd welcome any explanations why only [id] worked.

Resources