JGuizard
9/21/2017 - 3:33 PM

Ajax rest api call with axios

import React from 'react';
import Webcam from 'react-webcam';
import axios from 'axios'
import { DisplayResult } from './DisplayResult.js'
export class WebcamCapture extends React.Component {

  constructor(props) {
    super(props);

    this.state = { result:'',imgSrc: '' };
    this.capture = this.capture.bind(this);
  }

  setRef = (webcam) => {
    this.webcam = webcam;
  }

  capture = () => {
    var self = this;
    axios.post("http://localhost:5000/recognize", {
      image:this.webcam.getScreenshot()
    })
    .then(function (response){
      console.log(response);
      if(response.data.success == true)
      {
        //alert(response.data.emotion);
        self.setState({result: response.data.emotion});
      }
      else {
        self.setState({result: "Face not found :("});
      }
    })
    .catch(function (error){
      console.log(error);
    });
  };

  apiTest = () => {
    axios
      .get("http://localhost:5000/hello")
      .then(res => alert(res.data.msg))
      .catch(err => console.log(err))
  };

  render() {
    var result = '';
    if(this.state.result !== '')
    {
        result = <DisplayResult result={this.state.result} /> ;
    }
    console.log(result)
    return (
      <div>
      <div>
        <Webcam
          audio={false}
          height={600}
          ref={this.setRef}
          screenshotFormat="image/jpeg"
          width={800}
        />
      </div>
      <div>
        <button onClick={this.capture}>Capture photo</button>
      </div>
      <div>
      {this.state.imgSrc}
      {result}
      </div>
    </div>
    );
  }
}