0

I have a button and a text bar. when the button is clicked, it will send the url entered in the text bar to an API and get the response. I think this can be solved with the setState() Callback function. But i am Not able to understand how to implement it.....

 class App extends Component {
constructor() {
super();
this.state = {
input:'',
imageUrl:''
}
}
 onInputChange=(event) => {
 this.setState=({input: event.target.value});
 }
 onButtonSubmit = () => {
 app.models.predict(Clarifai.COLOR_MODEL,this.state.input).then(
    function(response) {
    console.log(response);
   },
    function(err) {
  // there was an error
}
);
}
 render() {

        <ImageLinkForm onInputChange={this.onInputChange} onButtonSubmit= 
 {this.onButtonSubmit} />       

    <FaceRecognition imageUrl={this.state.imageUrl} />
  </div>   
);
  }
}
 export default App;
3
  • 2
    You should format your code better so it's readable and clarify what you're asking. Commented Nov 24, 2018 at 21:04
  • Welcome to Stack Overflow and to the world of React. When we define the constructor() method, it will automatically be called with the props object and yes this is the same props object you use in functional components. When you define super() you also have to pass in props like so: super(props);. Commented Nov 25, 2018 at 2:07
  • @CodeDraken, thanks i will keep that in mind next time :) Commented Nov 25, 2018 at 6:48

1 Answer 1

1

Below is a demonstration on how to send an http request by using the url entered in a textbox.

Note you used the syntax for setState incorrectly. setState is a function and should called like so this.setState({ ... });

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ""
    };
  }
  
  onInputChange = event => {
    this.setState({ 
      input: event.target.value
    });
  };
  
  onButtonSubmit = () => {
    fetch(this.state.input)
      .then(() => {
        alert(`Success!`);
      })
      .catch((err) => {
        alert(`Failure: ${err}`);
      });
  };
  
  render() {
    return (
      <div>
          <input type="text" onChange={this.onInputChange}/>
          <button onClick={this.onButtonSubmit}>Submit URL</button>
      </div>
    );
  }
}


ReactDOM.render(
  <App/>,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.