0

I have 3 components/pages Home, page1, page2 and I'm sending props from home and calling page1

<Link
  style={{ textDecoration: "none", color: "inherit" }}
  to={{
    pathname: "/page1",
    Props: { categoryID: val.id, categoryName: val.name }
  }}
/>;

Then page 1 is getting these props in the constructor and defining states

class BuyerItems extends Component{
    constructor(props) {
        super(props);
        this.state = {
          id: props.location.aboutProps.categoryID,
          name: props.location.aboutProps.categoryName,
          gigs:[],
        }
        this.getGigs();
      }

Now from here if I go to page2 through link and then press browser back button it gives following error

TypeError: Cannot read property 'categoryID' of undefined

How to get these props or states from history and where to write that code? error

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
Ruma
  • 86
  • 1
  • 18
  • clicking the back button will cause the page to reload hence all the state which is saved in browsers memory will be lost, to prevent that you need to persist the state you can do that in localStorage – Berserk Guts Aug 28 '21 at 12:37
  • 1
    can you please explain how to persist these states – Ruma Aug 28 '21 at 12:38
  • refer to this https://stackoverflow.com/questions/47495696/react-router-how-to-restore-state-after-browser-back-button – Mahesh Aug 28 '21 at 12:54

2 Answers2

1

Your only issue is that you need to pass your props in the state object as @Manu suggested & not as a random property name like you are doing now. I made a repo for you here. as you can see the properties passed in the react-router's state object are persisting after pressing back button in sandbox's window, but the ones I put as props are not.

e.a.
  • 919
  • 4
  • 9
0

You shouldn't be passing data through links like that since it can be inconsistent; A better way would be to push your data to url as query parameters,so for example your page2 will have a url similar to

{baseUrl}/page2?id=someCategoryId&name=someCategoryName

then in your rusulting component you could fetch and parse the query:

const searchParams = new URLSearchParams(location.search);

better yet refer this: https://reactrouter.com/web/example/query-parameters

Anuja
  • 908
  • 6
  • 11