Thanks @vipatron for sharing it with me but, my case is different as I am trying to call api every time when the state changes not only once. So, my problem is not when and where exactly call my api, I want to make the call every single time state changes
my Apologies. I was thinking that a different lifecycle hook (willUpdate) might do the trick, but what about onChange? I don’t know React super-well yet, but all my reading thus far suggests those two as candidates, although I’m not that familiar with how to handle asynchronous calls.
handleChange = (event) => {
event.preventDefault(); // May or may not be necessary depending on what you are doing
const { value } = event.target;
const endpoint = `https://www.myapi.org/${value}`;
fetch(endpoint)
.then((response) => response.json())
.then((data) => {
// Do stuff with data and then call this.setState();
});
}
// ...
render() {
return(
<div>
<form onSubmit={(e) => this.handleSubmit(e)}>
<input
type='text'
placeholder='someone@example.com'
value={ this.state.email}
onChange={this.handleChange} />
<button type='submit'>Check</button>
</form>
{/* <section>{ Render messages here }</section> */}
</div>
);
}
EDIT: basically what @vipatron suggested just literally a minute before me!
Every state change triggers a render by default, so technically you can attach your api request before your setState or within its callback, however if you want more precision in which particular state or props change that you want your api call to be triggered with, you can use the componentDidUpdate() lifecycle method where the previous state (or props) are passed in as arguments and can be used to compare with your current state to trigger your call
@honmanyau the problem with this way is, I am not able to type in textfield. it sends a request every time I press a key but, what I want to achieve is sending a request with what I type and continuously. what I mean by that:
the solution you provided:
let’s say I type
a
it doesn’t show that I typed ‘a’ while it calls api with and if I continue to type, let’s say then I type
b
again it doesn’t show typed letter in textfield and calls api with ‘b’
what I want to achieve is the following behaviour:
pressed 'a’
a fetch('api/a');
pressed 'b’
ab
fetch('api/ab');
.
.
.
and so on
and when I press submit, calls api with the current value I have in text field and then reset it