Issue
I am having trouble redirecting from one page to another in react. So basically I have express server to serve the data React requires, and after getting the data in React from the server, I want to display that result in another page by redirecting to that page.
My code for fetching the data from express is:-
function handleSubmit(e) {
var webData;
e.preventDefault();
fetch("/getResults",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "post",
body: JSON.stringify(FormInfo)
})
.then((res) => res.json())
.then((data) => {
console.log(data);
webData = data;
<Redirect to="/resultpage" /> //1
})
.catch(err => {
console.error(err);
});
console.log(webData);
<Redirect to="/resultpage" /> //2
if (webData != null) {
console.log(webData);
<Redirect to="/resultpage" /> //3
}
// .then((data) => setData(data.postName));
}
I have tried Redirecting at all three positions 1,2 and 3 but to no avail. I even tried redirecting as soon as handleSubmit
function is called, but then it just re-renders my form page.
Please help me redirect to my resultpage. Using <Link>
in my header is working but I am able to go to another page, but redirecting is not working here.
I am just self learning with no experience in React, so excuse my mistakes if I haven’t followed any React standards.
Solution
JSX / Components have to be returned from the render function.
You can’t just slap them into the middle of any old function.
When dealing with asynchronously acquired data (such as you have with Ajax) store the result in the state.
Have the render function read the state and conditionally return a React Router <Redirect>
.
Answered By – Quentin
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0