0

i'm getting absolutely no response from calling my api in react:

constructor(props) {
        super(props);
        this.state = {
            team: {}
        }
    }

    getData() {
        axios.get('http://game.test/api/characters')
            .then(response => this.setState({ team: response.data.characters }));
     }

    componentDidMount() {
        this.getData();
        console.log(this.state);
    }

the state is empty and if I console.log anything in .then, the console is also empty (like that part of the code is not reachable). Also on Network tab everything seems to be okay (status 200 & correct data).

3 Answers3

0

setState is async so in console.log(this.state) will execute before this.getData() in the componentDidMount. if you want to log the fetch result/error put log in getData with async/await:


constructor(props) {
        super(props);
        this.state = {
            team: {},
            error: ""
        }
    }

    getData = async () => {
        await axios.get('http://game.test/api/characters')
              .then(response => this.setState({ team: response.data.characters }))
              .catch(error =>  this.setState({error: error}))
        console.log(this.state)  //log fetch result/error 
          }

    componentDidMount() {
        this.getData();
        console.log(this.state)    //log init state 
    }

-1

Try this, it will work

App.js

import Child from "./Comp/Chid";

export default function App() {
  return (
    <div className="App">
      <Child />
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Comp/Child.js

import React from "react";
import axios from "axios";

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      team: {}
    };
  }

  async getData() {
    await axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((response) => {
        console.log(response);
        this.setState({ team: response.data.characters });
      });
  }

  componentDidMount() {
    this.getData();
    console.log(this.state);
  }

  render() {
    return <div>Hello</div>;
  }
}

export default Child;
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
-1

i dont see much problem with your code try the following if it helps

  1. first try to console.log(response) before updating the state
  2. try async getData () and await axios since you are fetching asynchronous operation
AhmedHosny
  • 41
  • 1
  • 7
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 16 '21 at 14:35