tateccf
tateccf

Reputation: 135

useLocation hook and Server Side Rendering error in Gatsby

In one of my pages I want to get the page number param from the path and to do it I am using the useLocation hook imported from @reach/router.

import { useLocation } from '@reach/router';

The path looks like this:

http://localhost:4000/joboffers/?page=7

And I am getting the page number from the path like follows:

const pageParam = Number(useLocation().search?.split('=')[1]);

Well, if I console.log the pageParam variable, in the console of the Browser I get the correct page number, BUT if I check the terminal in Visual Studio Code the value of the same variable is NaN and Gatsby throws the following error:

React Components in Gatsby must render both successfully in the browser and in a Node.js environment. When we tried to render your page component in Node.js, it errored.

Does anyone know why is that happening? If I skip the SSR everything is working fine!

Upvotes: 1

Views: 3043

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29305

Well, you perfectly spotted the issue. In the SSR (Server-Side Rendering) the window and other global objects are not defined yet (for obvious reasons, you are in the server, not in the client) so any reference to that variables will fail.

The solution (one of the many possibilities) is that simple as:

let pageParam;
if (typeof window !== "undefined") {
  pageParam = Number(useLocation().search?.split('=')[1]);
} else {
   pageParam = 0;
}

This only happens during the gatsby build because gatsby develop command runs the project in the client directly (summarizing a lot).

Upvotes: 1

Related Questions