I am new to React and I am creating a website where the user can search for a query and the results are shown.
I have one component called: Searchbar
which contains two functions:
1) postQuery()
The user writes a query, which is sent via axios POST request to the backend when the user presses enter.
2) getQueryResult()
The backend searches the relative query and sends the results back via axios GET request.
Therefore the order is: postQuery()-->getQueryResult() so I think that postQuery() creates a promise that, if resolved, allows getQueryResult() to run.
However when the user clicks enter the first time, the results
variable does not get updated. Only when he clicks enter the second, third etc. time the setResult updates the results
. Therefore I think that my Promise of postQuery()
is not executed first.
This is what I get in console:
The first time, when enter is pressed for the first time, the results
does not get updated. But the second time yes.
Searchbar code
function Searchbar() {
const [query, setQuery] = useState("");
const [results, setResults] = useState(["myemptyinitiallist"]);
function postQuery(query) {
console.log(query)
var myParams = {
data: query
}
return axios.post('http://localhost:5000/api/query', myParams)
.then(function(response){
// console.log("Yes, it sends the query in JSON format to Flask");
})
.catch(function(error){
console.log(error, "Error on AXIOS post");
throw error; // don't fulfill returned promise
});
} // End of function: postQuery()
function getQueryResult() {
axios.get('http://localhost:5000/api/query')
.then(function (response) {
setResults(response.data); //set the value
// console.log(response.data["my_results"])
// console.log(results)
})
} // End of function: getQueryResult()
function handleEnter(query){
if (query != "") {
postQuery(query).then(() => getQueryResult());
console.log(results)
} else {
alert("The search query cannot be empty")
}
} // End of function: handleEnter()
return(
<div>
<SearchBar
onChange={(event) => setQuery(event)}
onRequestSearch={() => handleEnter(query)}
style={{
marginTop: 200,
marginLeft: 'auto',
marginRight: 'auto',
maxWidth: 800,
}}
/>
<ResultList/>
</div>
)
}