0

I have a state which I would like to set in one page and then access in another page. My solution is to create the state in _app.tsx and then pass it to each page.

My understanding is I can create the state in _app.tsx like this

function MyApp({ Component, pageProps }: AppProps) {
  const [accessToken, setAccessToken] = useState('')
  return (
    <ApolloProvider client={apolloClient}>
      <Component
        {...pageProps}
        setAccessToken={setAccessToken}
        accessToken={accessToken}
      />
    </ApolloProvider>
  )
}

How can I then access the state and setState functions in my pages? I tried

const Home: NextPage = ({setAccessToken}) => { 
...}

But I get the error: Property 'setAccessToken' does not exist on type '{ children?: ReactNode; }'.ts(2339)

How can I read the state I set in _app.tsx? Or am I going about this all wrong and should just use redux?

sev
  • 1,500
  • 17
  • 45
  • You should type the `Home` component as `const Home: NextPage<{ accessToken: string, setAccessToken: Dispatch> }>`. See [How to type a page component with props in Next.js?](https://stackoverflow.com/questions/69560905/how-to-type-a-page-component-with-props-in-next-js). – juliomalves Jul 24 '22 at 05:33
  • However, as @ToniBardinaComas pointed out, you may want to use [React Context](https://reactjs.org/docs/context.html) to make the state available to whatever components need it, rather than prop drilling. – juliomalves Jul 24 '22 at 05:34

1 Answers1

1

This is a typescript error that indicates that the prop setAccessToken is not expected for the Component. You can get rid of this error by updating/extending the Component interface inside AppProps. Btw what you are trying to do is very similar to the React.Context API. I would suggest using it instead of doing it yourself. You will get many advantages from doing so, like not having to send props all the way through to get/set the value on deeply nested child components.

Toni Bardina Comas
  • 1,670
  • 1
  • 5
  • 15
  • Hi some questions about your answer: 1) How would I update/extend the Component interface inside appProps? 2) I only really set and read the AccessToken in one place each. Would you still recommend Context over state? – sev Jul 22 '22 at 14:45