Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  175] [ 6]  / answers: 1 / hits: 10045  / 4 Years ago, mon, may 18, 2020, 12:00:00

I have a Next.js page that fetches data in the getInitialProps function and I want to reload this data from the browser without reloading the page, which would be unperformant and lose the user's scroll position. Is there some way to reload the initial props without reloading the entire page?


More From » next.js

 Answers
1

You could use a higher order component that stores the last initial props as state and can reload those by calling getInitialProps and setting the state to its return value. Here's a HOC that would do that:



import { NextPage, NextPageContext } from 'next';
import React, { useState, PropsWithChildren, ComponentType } from 'react';

/**
* Removes never-used context values to reduce bloat. Context values may come from server but then
* be used client-side because they are saved in initial props.
*/
function minifyContext(context) {
return { ...context, req: undefined, res: undefined };
}

const withSoftReload = Page => {
async function getInitialProps(ctx) {
return { context: minifyContext(ctx), ...(await Page.getInitialProps(ctx)) };
}
const omitContextFromProps = ({
context,
...props
}) => props;
const NewPage = props => {
// set inner page initial props to wrapper initial props minus context
const [initialProps, setInitialProps] = useState(omitContextFromProps(props));
async function softReload() {
setInitialProps({ children: null, ...(await Page.getInitialProps(props.context)) });
}
return (
<Page
{...{ ...initialProps, softReload }}
/>
);
};
NewPage.getInitialProps = getInitialProps;
NewPage.displayName = `withSoftReload(${Page.displayName})`;
return NewPage;
};

export default withSoftReload;


In your pages you would use it like this:



const MyPage = ({ data, softReload }) => (
<div>
{data}
<button onClick={softReload}>Refresh</button>
</div>
);

MyPage.getInitialProps = async (ctx) => {
// fetch data
};

export default withSoftReload(MyPage);

[#3780] Friday, May 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;