React-router location state object is empty

Viewed 348

I`m trying to persist state with react-router using a DateObject object from react-multi-date-picker library: https://shahabyazdi.github.io/react-multi-date-picker/date-object/ . But the object is emptied when I try to access the state after navigating.

let history = useHistory();
history.replace({pathname: "/", state: {date: new DateObject()});
history.push({pathname: "/another-path"});
let history = useHistory();
history.goBack();

let location = useLocation();
console.log(location.state.date);
import { BrowserRouter, Switch, Route } from "react-router-dom";

function Router() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/">
          <CustomDatePicker />
        </Route>
        <Route path="/another-path">
          <AnotherComponent />
        </Route>
      </Switch>
    </BrowserRouter>
  );
}

export default Router;

Before navigating

state before navigating

After navigating

state after navigating

2 Answers

Create a new state which is defined by new DateObject() and pass that through instead. So for example

this.setState({myNewState: new DateObject()})
// then pass it through
history.replace({pathname: "/", state: {date: myNewState});

or useState if its a functional component.

Hope that works

I found a solution! I used the method toDate() in the react-multi-date-picker library to convert the custom DateObject to javascript Date object and store it in state. For some reason, storing the DateObject() in the history stack, navigating away and coming back doesn't work! Thanks!

Related