Axios and Component State

What is State?

In anytime that we change the state of the component, the component will automatically render itself to the mobile devices screen

3 steps to implement State

  1. Set default or initial state for the class component

  2. Get the data and tell component’s state to update

Use this.setState({}) will auto trigger the UI update

Make sure that the component makes use of the state

When setState is called, it will trigger render()

// import React is must as React.createElement will be called in convert
import React, { Component } from "react";
import { View, Text } from "react-native";
import axios from "axios";

class AlbumList extends Component {
  state = { albums: [] };   // class level property

  componentWillMount() {
    axios.get("https://rallycoding.herokuapp.com/api/music_albums")
    .then(response => this.setState({albums: response.data}));
  }

  // Use render Method to help to return JSX Object
  render() {
    console.log(this.state)
    return (
      <View>
        <Text>Album List</Text>
      </View>
    );
  }
}
export default AlbumList;

Rule of State

  • Definition of state: a plain javascript object used to record and respond to user-triggered events.

  • When we need to update what a component shows, call this.setStates

  • Only change state with setStateI, do not do this.state

Last updated

Was this helpful?