I am creating a website where the user can search for a query and the results are shown.
I created two components: Searchbar
and ResultList
, both are functional components with hooks.
Searchbar
The user writes a query, which is sent via axios POST request to the backend when the user preses enter. The backend search the relative query and sends the results back via axios GET request. This is working.
ResultList
The ResultList state is initialised with an array called results
.
What I would like:
I want to set the results
array equal to the what it is returned from the GET request in the Searchbar.
Searchbar code
function Searchbar() {
const [query, setQuery] = useState("");
function handlePostQuery(query){
var myParams = {
data: query
}
if (query != "") {
axios.post('http://localhost:5000/api/query', myParams)
.then(function(response){
var instructions_div = document.getElementsByClassName("instructions")[0];
instructions_div.style.display = "none";
console.log("Yes, it sends the query in JSON format to Flask");
//Perform action based on response
})
.catch(function(error){
console.log(error, "Error on AXIOS post");
//Perform action based on error
});
axios.get('http://localhost:5000/api/query')
.then(function (response) {
console.log("AXIOS GET")
console.log(response);
})
.catch(function (error) {
console.log(error);
});
} else {
alert("The search query cannot be empty")
}
}
return(
<div>
<SearchBar
onChange={(event) => setQuery(event)}
onRequestSearch={() => handlePostQuery(query)}
style={{
marginTop: 200,
marginLeft: 'auto',
marginRight: 'auto',
maxWidth: 800,
}}
/>
<ResultList /> # I think I should set the new state of Resultlist here but not sure how
</div>
)
}
export default Searchbar;
ResultList code
function ResultList() {
const [results, setResults] = useState(["myemptyinitiallist"]);
if (results[0] !== "myemptyinitiallist") {
return (
<div className="resultlist">
This should appear only if results is different from "myemptyinitiallist"
</div>
)
} else {
return(
<h1>This should appear when results is empty</h1>
)
}
}
export default ResultList;
IDEALLY I would like NOT to use class components.