MiguelSlv
MiguelSlv

Reputation: 15123

How to access state from an handler on nextjs?

I have a handler defined by the custom app (_app), hook to the routeChangeStart event.

The handler should analyze the new path and store some result at state variable. The handler is a class member, yet it throws the error:

Unhandled Rejection (TypeError): this is undefined

Here the code:

import App from 'next/app';
import Router from 'next/router'
import { withRouter } from 'next/router'
import MyAppContext from '~/components/MyAppContext';


class MyApp extends App {

    state = {
      language: null
    };

    getCurrentLanguage(url){
        ...
    }

    handleRouteChange(url){
      console.log('App is changing to: ', url)
      this.setState (  //throws: Unhandled Rejection (TypeError): this is undefined
         {language: this.getCurrentLanguage(url)}
      )
    }
    componentDidMount = () => {

      this.setState({language: this.getCurrentLanguage()})
        Router.events.on('routeChangeStart', this.handleRouteChange)
      };

    render() {
      const { Component, pageProps } = this.props;

      return (
        <MyAppContext.Provider value={{ language: this.state.language }}>
          <Component {...pageProps} />
        </MyAppContext.Provider>
      );
    }
  }

export default withRouter(MyApp)

Upvotes: 0

Views: 394

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14365

The function is a class member, but this is dependent on the context of where the function is called not declared. You are passing the function reference to the listener which will call it from somewhere else, meaning this will not be referring to the class anymore.

You'll have to either bind it to this manually, or make it an arrow function.

handleRouteChange = (url) => {

// or

Router.events.on('routeChangeStart', this.handleRouteChange.bind(this))

Upvotes: 1

Related Questions