0

I can't get this combo to work. I think it's specifically due to having TypeScript in the mix? My syntax is as seen here but I get runtime issues. There are no compile errors but, when the func is encountered, I get:

this.foo is not a function

export default class App extends Component<Props> {
    render() {
        return (
            <Button title="A Button" onPress={this.buttonPressed} />
        );
    }

    buttonPressed() {
        this.foo().then(movies => {
            console.log(movies);
        });
    }

    async foo() { 
        try {
            let response = await fetch('https://facebook.github.io/react-native/movies.json');
            let responseJson = await response.json();
            return responseJson.movies;
        } catch (error) {
            console.error(error);
        }
    }
}
xanadont
  • 7,493
  • 6
  • 36
  • 49
  • When you pass the method as a callback, `this` will no longer reference the class instance. You may want to [take a look at this question](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback/23975783). – CRice May 02 '18 at 01:32
  • Oh, gosh, I knew this! Answered below. Thanks, my head hasn't been in React Native in quite a long time. – xanadont May 02 '18 at 04:27

1 Answers1

-1

As CRice noted, this is due simply to not having access to this in an anonymous callback. It can be solved by:

onPress={() => this.buttonPressed(this)}
xanadont
  • 7,493
  • 6
  • 36
  • 49