0

I'm using React 16.13.0. I have the following handler for submitting my React form to its endpoint ...

  const handleFormSubmit = (e) => {
    ...
     fetch(REACT_APP_PROXY + "/coops/", {
      method: "POST",
      body: JSON.stringify(NC),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          throw response; 
        }
      })
      .then((data) => {
        const result = data;
        window.location.href = "/" + result.id + "/people";
      }).catch(err => {
        err.text().then( errorMessage => { 
          setErrors({ errors: errorMessage });
        }); 
      });
  };

I was wondering if there is a more "React" way of redirecting to the next page. Right now, I'm doing

window.location.href = "/" + result.id + "/people";

which seems kind of hacky. Also, I'm not able to pass an object to the next page, which I have on the page executing the submit (The "data" object is what ideally I'd like to pass to the next page). Thus, when the redirect page loads, I'm forced to execute another fetch call to retrieve that object again.

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

0

React, Passing objects between page loads / location changes:

  • you can use the localStorage/sessionStorage as described in the accepted answer here.
  • or you use React Context or Redux to store the object in global state that is shared across the application

React, Routing & Passing objects:

First of all, nothing is wrong with updating window.location. It is a valid way to update the current page. Leaving it as is and using sessionStorage to pass your object will most likely be the fastest way to solve your problem. That being said, there are me more optimized solutions out there that feel more like react: Try React Router for instance. It also lets you pass objects between routes by passing them down as props to the other pages.

react-router-dom hooks example:

import { useHistory } from "react-router-dom";

const myComponent = () => {
     const history = useHistory();

...
     .then((data) => {
        const result = data;
        // access state via this.props.location.state.result
        history.push({
           pathname: "/" + result.id + "/people",
           state: {result}
        });
      }).catch(err => {
        err.text().then( errorMessage => { 
          setErrors({ errors: errorMessage });
        }); 
      });
}

Find more information about react-router-dom here.

Andre
  • 4,185
  • 5
  • 22
  • 32