I have two separate pages in my React application. There are search bars in both pages. In the second page it works fine as the list from where I implement search operation is located in that page. As I have a search bar in the first (homepage) too, it's expected that when inputting something inside search bar, it'll navigate to the second page and show the selected item.
I managed to pass the inputted text to the second page and used useEffect() from the second page to trigger fetchData() function. But transfers inputted text to the second page but does not always trigger the fetchData() function.
This is my first page from where the searched input is passed to the /second page
const HomePage = ({ envVar }) => {
const [data, setData] = useState("")
const navigate = useNavigate();
const navigateNextPage=()=>{
navigate('/second',{state:{searchedWaybill:data}});}
return ( <input type="search" defaultValue=""
onChange={(e) => setData(e.target.value)}/>)
}
This is my second page:
const SecondPage = ({envVar}) => {
// I used useEffect to reload page, so fetchData() function is triggered
useEffect(() => {
if (location.state != null) {
{
var currentDocumentTimestamp =
new Date().getTime();
var now = Date.now();
var tenSec = 10 * 1000;
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
window.location.reload();}
fetchData(location.state.searchedWaybill)
};
}
}, []);
const [loading, setLoading] = useState(false);
const [tableData, setTableData] = useState([]);
const searchedWaybill = location.state == null? "": location.state.searchedWaybill;
useEffect(()=>{
setLoading(true);
fetch((envVar?.opsAgentEndpointUrl || networkConstants.baseUrl) + networkConstants.endPoints.getOpenFeedbacklist + currentPage + '&size=8&continue')
.then((response) => response.json())
.then((json) => { setLoading(false); setTableData(json)});
},[currentPage]);
const [innerValue, setInnerValue] = useState("");
const fetchData = (searchInput) => {
fetch((envVar?.url + searchInput)
.then(response => {
if(!response.ok) {
throw new Error("error in fetch"); }
return response.json()
})
.then(data => {
if(data.stat === "fail") {
throw new Error(data.message);
}
var list = [];
list.push(data);
setDatajson(list);
setTableData(list);
})
.catch(function(err) {
console.log(err)
});
}
return ( <div>
<svg ... onClick={ () => {fetchData(innerValue)}}>
<path d="M ......... fill="#D40511"/>
</svg>
</div>
)
}