Reputation: 111
Can y'all coding experts help me with this please..
The code is shown below.
I am trying to implement a simple search page. You will be redirected to this page containing the answer from the search criteria that you input in a previous page. In this current page, you can also modify the answer that you got by inputting a new search criteria, then you click search to get a new answer, replacing the old one. Ideally when inputting a new search criteria, it should replace the old querystring in the url of the page, and then the page will refresh, and then the new query string is used to get the new answer, which will be displayed in the refreshed page. So here is what i write.
import React from 'react';
import { Link } from 'react-router-dom';
const querystring = require('querystring');
class SearchResult extends React.Component {
constructor(props) {
super(props);
this.state = {
answer: '',
input: '',
};
this.getEntries = this.getEntries.bind(this);
this.updateRes = this.updateRes.bind(this);
this.handleDetailChange = this.handleDetailChange.bind(this);
}
componentDidMount() {
this.updateRes();
}
getEntries = async () => {
this.setState({
loading: true,
});
const response = await fetch(
this.props.location.pathname + this.props.location.search
);
const body = await response.json();
return body;
};
updateRes = async () => {
this.getEntries()
.then((resolve) =>
this.setState({
answer: resolve.answer,
})
)
.catch((err) => console.log(err));
};
handleInputChange(event) {
this.setState({
input: event.target.value,
});
}
render() {
let currentPath = this.props.location.pathname;
let qString = querystring.stringify(this.state.input);
return (
<div id='result-page'>
<div>This is the answer : {this.state.answer}</div>
<label htmlFor='input'>Input here:</label>
<input type='text' name={'input'} onChange={this.handleInputChange} />
<Link to={`${currentPath}?${qString}`} onClick={this.updateRes}>
<button> Search </button>
</Link>
</div>
);
}
}
export default SearchResult;
What it does is not what I expected. When i click search, the answer I got was based from the previous page criteria/querystring (not the new one that i just inputted). This is maybe because the onClick
of <Link/>
is executed before the query string is updated with a new one, which is not what i want! How do I make the OnClick handler executed after the url has been changed and refreshed by link?
Upvotes: 0
Views: 820
Reputation: 1160
Usually the scheme is like below (spoiler - Routes should be used):
Upvotes: 1
Reputation: 4663
That's because in onClick
you call an async
function. You have to await
for it's result, I guess. Try it like this:
onClick={async () => {await this.updateRes();}}
Upvotes: 0