0

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;

1 Answers1

1

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}>.

MrSrv7
  • 585
  • 8
  • 22
  • Is it possible to put these functions and states outside of class menu? And return data without json.stringify, because inside class menu there functions that process json with their states and etc – UgandaWarrior Jun 29 '22 at 06:07
  • No. States are React's things available inside the Component class. State values and setState functions are implemented. These are not accessible outside the react components – MrSrv7 Jun 29 '22 at 15:21