Edgaras Karka
Edgaras Karka

Reputation: 7852

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

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.

Upvotes: 9

Views: 19725

Answers (3)

Marzieh Mousavi
Marzieh Mousavi

Reputation: 1624

In my case, the problem was the pathname. you should write the exact url to send state.

target url=/page1/page2/page3/

 const path = '/page1/page2/page3';
 history.push({ pathname: `${path}`, state: {item: myItem}}); //state will be undefined
 const path = '/page1/page2/page3/';
 history.push({ pathname: `${path}`, state: {item: myItem}); //state will be {item: myItem}

Upvotes: 0

Tenusha Guruge
Tenusha Guruge

Reputation: 2290

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.

Upvotes: 7

johnny peter
johnny peter

Reputation: 4872

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).

Upvotes: 1

Related Questions