i have created a form which calls the search function after pressing submit button. I want the results of the search to be displayed in another function component (have used React Context for this purpose).
However, i faced an issue where i cannot link it to another route /yourstage/results
WITHOUT refreshing the page. If the page is refreshed, my seachResult stored in state will be gone.
import React, { Fragment, useState, useEffect, useContext } from "react";
import { withRouter, Link } from "react-router-dom";
import searchResultContext from "./SearchResultContext";
const Search = () => {
const [wave, setWave] = useState("$perc");
const [pack_hu, setPackHu] = useState("$perc");
const { searchResult, setSearchResult } = useContext(searchResultContext);
useEffect(() => {
console.log(JSON.stringify(searchResult));
}, [searchResult]);
//submit a form to search
const submitSearch = async (e) => {
e.preventDefault()
try {
const response = await fetch(
`http://localhost:5000/yourstage/search/${wave}/${pack_hu}`,
{
method: "GET",
headers: { "Content-Type": "application/json" },
}
);
setSearchResult(await response.json());
//Reset Form and State
document.getElementById("searchForm").reset();
setWave("$perc");
setPackHu("$perc");
} catch (error) {
console.error(error.message);
}
};
//return the form html
return (
<Fragment>
<h1 className="text-center mt-3">Search</h1>
<form id="searchForm" onSubmit={submitSearch}>
<div className="form-group row">
<label htmlFor="Wave" className="col-sm-2 col-form-label">
Wave:
</label>
<div className="col-sm-10">
<input
type="text"
className="form-control"
placeholder="Wave Number"
maxLength="10"
onChange={(e) => setWave(e.target.value)}
/>
</div>
</div>
<div className="form-group row">
<label htmlFor="pack_hu" className="col-sm-2 col-form-label">
Pack HU:
</label>
<div className="col-sm-10">
<input
type="text"
className="form-control"
placeholder="Pack HU"
maxLength="10"
onChange={(e) => setPackHu(e.target.value)}
/>
</div>
</div>
<div className="row text-center mt-5">
{/**Search based on parameter*/}
<div className="col-6">
<button type="submit" className="btn-lg btn-primary">
<Link to="/yourstage/results">Search</Link>
</button>
</div>
</div>
</form>
</Fragment>
);
};
export default withRouter(Search);