Having trouble getting changes to persist with async function when called from an onClick event handler. I have the functions I am calling:
retrieveData = async () =>{
try {
console.log(1)
console.log(this.state.ID)
const url = this.baseUrl + "api/" + this.state.ID
let response = await fetch(url, {mode: "cors"})
const data = await response.text()
this.setState({testVal: data})
console.log(data)
} catch (e) {
console.error(e)
}
}
The above function works when I put its contents in componentDidMount() and hardcode the state ID. But not when I try to call the retrieved data function like so, so I assume the following snippet is where the error is.
render() {
return(
<div>
<div>
<form>
<label>
ID:
<input type="text" onChange={e => this.setState({ID: e.target.value})}/>
</label>
<input type="submit" onClick={async () =>{await this.retrieveData();}}/>
</form>
</div>
<div>
{this.state.ID}
{this.state.testVal}
</div>
</div>
);
}
Im fairly new to reactJS, so I am sure it is something simple. When I click the submit button, I see the console spit out the 1, and then the ID I had just entered, and then both immediately disappear. When I check to see if the fecth is happening, I dont see any calls to the api like when I tested with a hardcoded url with componentDidMount(), but I want to be able to take user input, just a little unsure how to. I believe I have checked just about every SO question I can find on this, so I really am lost. If more info is needed please let me know, thank you.
{mode: "cors"}will not resolve various CORS error from the server you are making requests to. Also this could be failing at the request level, at the.text()if it's not text, but application/json