UgandaWarrior
UgandaWarrior

Reputation: 1

How to get response from get request (React)?

I am new guy in react, so how to put value that i receive from jsonHandler function into render return statement?

I've tried a lot, but i always have the same result. Console.log(jsonData) in jsonHandler function returns value that i need, but function jsonHandler returns promise and idk how to handle it. It doesn't matter to use axios.get or fetch().

async function jsonHandler () {

    let jsonData;
    const url = "http://localhost/index.php";

    await axios.get(url)
        .then(({data}) => {
            jsonData = data.data;
        });
    console.log(jsonData);                        //returns that i need
    return jsonData;
}

class Menu extends Component {


    ...


    render() {
        console.log(jsonHandler());                       //returns promise
        return <div className="MenuWrap">{this.mainHandler(Here Must Be Data From jsonHandler)}</div>;
    }
}

export default Menu;

Upvotes: 0

Views: 1087

Answers (1)

MrSrv7
MrSrv7

Reputation: 781

You can do it this way. Make use of states for reactive updates. I referred to https://stackoverflow.com/a/45744345/13965360 for the setStateAsync function, which sets the state value asynchronously and means it will wait till the API call is done. You can use try and catch with await if you are using async instead of then and catch blocks.

const url = "http://localhost/index.php";

class Menu extends Component {
  state = {
    jsonData: {},
  };

  //creating a function that sets the state asynchronously

  setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve);
    });
  }

  //   Fetch the data
  async jsonHandler() {
    try {
      const response = await axios.get(url);
      this.setStateAsync({ jsonData: response.data });
      console.log(this.state.jsonData); //returns that i need
    } catch (error) {
      throw new Error(error);
    }
  }

  render() {
    return (
      <div className="MenuWrap">
        {Object.keys(this.state.jsonData).length &&
          JSON.stringify(this.state.jsonData)}
      </div>
    );
  }
}

export default Menu;

If you want to do the API call instantly once the component renders, you need to put it in the componentDidMount lifecycle.

Like, async componentDidMount() { await this.jsonHandler(); }

Or, if you want to make the API call upon clicking a button, you need to bind the method to the listener like <button onClick={this.jsonHandler}>.

Upvotes: 1

Related Questions