Search code examples
javascriptreactjsvariablesoutputhierarchy

How to save an output in console as a variable in react?


I am doing the project from web development course, and I want to modify it a bit, but I'm stuck. I want to save this output -> response.outputs[0].data.regions[0].data.concepts[0].name as a variable, and then pass it to a child component, however, all the ways I tried to do it didn't work. Any suggestions? Thanks!

 ``` onSubmit = () => {
    this.setState({imageUrl: this.state.input});
    app.models
    .predict(
      Clarifai.RANDOM_MODEL,
      this.state.input)
      .then(
          function (response){
           console.log(response.outputs[0].data.regions[0].data.concepts[0].name);
        },
        function(err){
          console.log(err)
        }
      );
    } ```

Solution

  • You can't return the response from an asynchronous call.

    Inside the then callback, store the data in the component's state.

    When you render the child component, pass the data from the state through a property.

    Since the state might not have the desired value yet, you need to test for that and provide suitable alternative content.

    e.g.

    if (myStateVariable) {
        return <Foo value={myStateVariable} />
    }
    return <LoadingIndicator />