Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router's location state becomes undefined on change of route

Tags:

I want to store url query as a state on location.

~   history.push({
+     ...history.location,
+     search: query.toString(),
+     state: {
+       myState: query.toString(),
+     },
+   })

I suspect get state when a route change, but state become undefined when I back from other route.

like image 977
Edgaras Karka Avatar asked Jun 17 '19 11:06

Edgaras Karka


2 Answers

This is how state (which comes from the History API) works. State is attached to a location in a session and does not exist (or rather, is null) when you navigate directly to a page.

In general, I would not recommend using location.state for passing anything but temporary data (like a redirect location). If you need data attached to a location I would recommend using either path params or search params and having a store that you can lookup that data from.

// path params
{ pathname: `/path/name/${SOME_ID}` }
// search params
{ search: `?someID=${SOME_ID}` }

If you really want to use location.state, your route will need to have some sort of backup plan for using some default value when location.state is null.

like image 126
Tenusha Guruge Avatar answered Sep 29 '22 09:09

Tenusha Guruge


Its the second argument in history.push(path, [state])

history.push("path/you/want/to/push/to", { state: myState: query.toString() })

You can look for the state from location.state

Note: Also the state will not be available in other routes. Each route has its own state which is inaccessible by other routes.

Its stated in the docs here

Normally you just use a string, but if you need to add some "location state" that will be available whenever the app returns to that specific location, you can use a location object instead. This is useful if you want to branch UI based on navigation history instead of just paths (like modals).

like image 44
johnny peter Avatar answered Sep 29 '22 09:09

johnny peter