React-Native state undefined

1.1k Views Asked by At

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)

3

There are 3 best solutions below

0
On BEST ANSWER

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)} />
0
On

It's no matter of setState. Use normal class method will be ok:

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

Write a bit more...

Actually, changeName in your code is a class property, not a class method. We can transform these code with es5 syntax(ignore async and some other unnecessary code):

function Dashboard() {
  ....
  defineProperty(this, 'changeName', async function() {
     // "this" here doesn't point to Dashboard context
     this.setState({ .... })
  })
}
0
On

You need to bind the function to this. So change the following line:

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

To the following:

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