1

====P.S. I found a solution and wrote in comments.

I want to make a form and show its server response in another domain after redirect. A request is sent from /, and server handles the request, then browser sees response from server at /result domain.

Conventionally, It's very simple. This is written as

====index.html====

<form action="/result" method="POST">
  <input type="text" placeholder="Your Name" />
  <input type="submit" />
</form>

There are more examples like: https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_post

I want to write React code like above, however, I have difficulty in browser history and redirecting with params. My react looks like below. It doesn't pass browser sent response to /result domain.

====App.js====

function App() {
  return (
    <BrowserRouter>
      <div>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/result">
            <Result />
          </Route>
        </Switch>
      </div>
    </BrowserRouter>
  );
}

function Home() {
  const [submitted, setSubmitted] = useState(false);
  const [content, setContent] = useState("");
  const history = useHistory();

  const handleSubmit = (event) => {
    event.preventDefault()
    fetch('https://api.example.com')
    .then(response => response.json())
    setSubmitted(true);
    history.push("/"); // because Redirect override history, this line enables browser back button (I guess there should be a smarter way)
  }
  if (submitted) {
    return <Redirect to='/result' /> // I want to pass fetched API response to /result
  }
  return (
  <div>
    <h1>Send content to server</h1>
    <form onSubmit={handleSubmit}>
        <label>
          Content:
          <input name="content" type="text" {...bindContent} />
        </label>
        <input type="submit" value="Submit" />
        </form>
  </div>
  );
}

function Result(response) {
  return <h2>Browser received {response}</h2>
}
Watanabe.N
  • 1,549
  • 1
  • 14
  • 37
  • I found doesn't override history. Now I don't need to call usehistory https://reacttraining.com/react-router/web/api/Redirect/push-bool – Watanabe.N Mar 19 '20 at 12:41
  • I finally found solution. To access props, use useLocation() in function component. Thanks to https://stackoverflow.com/questions/37516919/react-router-getting-this-props-location-in-child-components – Watanabe.N Mar 19 '20 at 12:55

1 Answers1

0

From your above comment it seems that you found the solution to the problem but to anyone having the same issue what you want to do is send the data on submit through useHistory hook as const history = useHistory(); and then history.push("/result", { params: data }); (the second argument is the state so that would contain the object params ) and in the component you want to access the params you would use the useLocation hook as const location = useLocation(); and then location.state.params so in the home component you would do

Home.js

const handleSubmit = event => {
 event.preventDefault();
 fetch("https://jsonplaceholder.typicode.com/users")
 .then(response => {
  return response.json();
   })
 .then(data => {
   history.push("/result", { params: data });
   });
 };
// Rest of the Code

and in the component you want to use it in

Result.js

 import React from "react";
 import { useLocation } from "react-router-dom";
 export default function Result() {
   const location = useLocation();
   const data = location.state.params;
   console.log(data);
   return <h2>Browser received </h2>;
}

Working Example on Codesandbox here

Abdullah Abid
  • 1,541
  • 3
  • 10
  • 24
  • Thank you for an answer, but this doesn't work: Expected an assignment or function call and instead saw an expression no-unused-expressions – Watanabe.N Mar 19 '20 at 12:07
  • i forgot the `return` i have updated the answer, try it again – Abdullah Abid Mar 19 '20 at 12:25
  • Thank you. It still doesn't work in promise chain. When I move return out from handleSubmit, it redirects, but props in Result is empty. – Watanabe.N Mar 19 '20 at 12:34