I have the following Next.js code in a component:
import { useSearchParams } from 'next/navigation';
const searchParams = useSearchParams();
const currentPage = parseInt(searchParams.get('page') || '', 10) || 1;
I get this error in the Storybook stories
:
TypeError: Cannot read properties of null (reading 'get')
The offending line is this:
const currentPage = parseInt(searchParams.get('page') || '', 10) || 1;
After reading the official Storybook docs, I tried this:
const meta: Meta<typeof ItemModal> = {
title: 'Example/List',
component: ItemModal,
parameters: {
nextjs: {
appDirectory: true,
navigation: {
searchParams: {
page: '1',
},
},
},
},
};
Also this:
navigation: {
segments: [
['page', '1'],
],
},
And this:
navigation: {
segments: [['?page=1']],
},
But I'm still getting the same error.
What am I doing wrong?
Also posted here.
Update: I did console.log('seachParams:', searchParams);
and it's returning null
even though I did this.
This is the full component.
useSearchParams
hook only works with client components in next according to docs.
Try to add "use client"
on top of your component.