javascripthtmlcssreactjsclarifai

How to print Clarifai API returned response?


help... I'm making a project that detects food ingredients using Clarifai API Food model. When the API scans the image, it returns the response via console.log. How do you get THAT output from the API (console.log) and print it in the webpage. sorry, newbie aspiring web dev here.Image of website,console.log, and JS code


Solution

  • Instead of console logging the response, you should define a key value pair in the state of the component:

    // the initial value of each key in state should match what data you are storing
    this.state = {
      input: '',
      foodUrl: '',
      prediction: {},
    };
    

    After the file has received the API response, instead of console logging the response you would write:

    this.setState({ prediction: response.outputs[0].data.concepts[0] });
    

    Next you would pass it in to the component you are using to display the response within the render portion of App.js:

    <ComponentToRenderAPIResponse prediction={this.state.prediction} />
    

    Within that child component, you would then write something like this within the render portion:

    render() {
      return (
        <div>`Detected Food: ${prediction.name}`</div>
        <div>`Prediction Value: ${prediction.value}`</div>
      )
    }
    

    Instead of storing the entire object displayed in your console, you could just access the name and value key value pairs and store them as separate fields within your state object. Then pass both the name and value as different props to the child component. Also you might want to consider different html tags than the divs I used above as well as adding CSS styling to both tags.