Search code examples
reactjsreact-nativereactjs-native

React-Native state undefined


I'm using classes for the first time in react-native but for some reason I can not change a state. I checked if it was the API but the API works fine. The bootstrap and everything else works fine to but the this.setState({ name: response.data.name }); does not work for some reason. Does anybody know what I am doing wrong?

import React from "react";
import { StyleSheet, View, Text, AsyncStorage, Button } from "react-native";
import axios from "axios";

export default class Dashboard extends React.Component {
  constructor() {
    super();
    this.state = {
      token: "",
      response: [],
      supported: true,
      displayName: "",
      id: 0,
      name: "",
      phone: 0,
      website: ""
    };
    this._bootstrap();
  }

  _bootstrap = async () => {
    const token = await AsyncStorage.getItem("accessToken");
    this.setState({ token: token });
  };

  changeName = async function() {
    try {
      response = await axios.get("general/organization/own/default");
      this.setState({ name: response.data.name });
      return;
    } catch (error) {
      console.log(error);
      return;
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <Text>name: {this.state.name}</Text>
        <Button title="change name" onPress={this.changeName} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  }
});

error: this.setState is not a function. (In 'this.setState({name: response.data.name})', 'this.setState' is undefined)


Solution

  • To be able to use this inside a function you will need to bind it to the class. So a few ways you have to solve this are:

    Create an arrow function

    changeName = async () => {
      try {
        let { data: { name } } = await axios.get(url);
        this.setState({ name });
      } catch (err) {
        console.log(err);
      }
    };
    

    Bind the function on the constructor

    constructor(props) {
      this.state: {},
      changeName: this.changeName.bind(this),
    }
    

    Bind it on the <Button/>

    <Button title="change name" onPress={this.changeName.bind(this)} />