I'm having a website where I show different kinds of projects to the user. I'm using Hasura
, NextJS
and Apollo
to make this happen. The problem I have now is that every time I come back to the home page (where I show my projects) the query is getting fired again and has to load all over again. I want to save the data in my cache, but I'm not sure how to do that.
This is how I do it now:
I'm calling the query, when its done loading, I return my Home component with the data.
const ProjectList = () => {
const { loading, error, data } = useQuery(GET_PROJECTS);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
console.error(error);
return <div>Error!</div>;
}
return <Home projects={data.projects} />;
};
export default withApollo({ ssr: true })(ProjectList);
In the home component I know can use the data:
const Home = ({ projects }) => {
// rest code...
}
I create my apolloClient as the following:
export default function createApolloClient(initialState, headers) {
const ssrMode = typeof window === 'undefined';
let link;
if (ssrMode) {
link = createHttpLink(headers); // executed on server
} else {
link = createWSLink(); // executed on client
}
return new ApolloClient({
ssrMode,
link,
cache: new InMemoryCache().restore(initialState),
});
}
Is there a way I can save the data in the cache, so I don't have to wait for the loading state every time I come back to the home page?
You can use the prebuild feature of nextjs. For this you need to call getStaticProps in your ProjectList.jsx file. There you have to import your apollo client as well as your query, then initialize the client and do the query:
export async function getStaticProps() {
const apollo = require("../../../apollo/apolloClient"); // import client
const GET_PROJECTS = require("../../../apollo/graphql").GET_PROJECTS; // import query
const client = apollo.initializeApollo(); //initialize client
const { data, error } = await client.query({
query: GET_PROJECTS
});
if (!data || error) {
return {
notFound: true
};
}
return {
props: { projects: data.projects } // will be passed to the page component as props
};
}