Search code examples
javascriptreactjsnative

How to solve an error 'cb is not a function' in React Native?


current code

Index.js

import Auth from 'app/src/common/Auth';

export default class Index extends React.Component {

async componentDidMount() {
    this.props.navigation.addListener('willFocus',
      Auth.me().then(async (response) => {
        await this.setState({ isLoggedIn: response });
      }));
}

...
}

Auth.js

import axios from 'axios';
import { ENV } from 'app/env';
import { AsyncStorage } from 'react-native';

const { baseApiUrl } = ENV;

export default {
  async me() {
    try {
      let result = false;
      let token = await AsyncStorage.getItem('token');
      token = token.replace(/"/g, '');
      const response = await axios.get(`${baseApiUrl}/api/auth/me`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (response.data) {
        result = true;
      }
      return result;
    } catch (error) {
      console.log(error);
    }
  },

};


error

I keep getting this error.

TypeError: cb is not a function. (In 'cb(data)', 'cb' is an instance of Promise)

I would appreciate it if you could give me any advice.


Solution

  • Its hard to tell without detail knowledge of your code (or react), but from the name i would expect this.props.navigation.addListener to take a callback function. Instead you pass a promise.

    this.props.navigation.addListener('willFocus',
      Auth.me().then(async (response) => {
        await this.setState({ isLoggedIn: response });
      })
    );
    

    Try changing the code to:

    this.props.navigation.addListener('willFocus', () => {
      Auth.me().then(async (response) => {
        await this.setState({ isLoggedIn: response });
      })
    });