Derek Jin
Derek Jin

Reputation: 672

Gatsby Link State is lost when I refresh the page

I am sending state data using state props in the Link component provided Gatsby.

<Link
  to={`/photos`}
  state={{ photoData }}
>
  View Photo
</Link>

When I Click View Photo Link, it goes to photos page and I can get the photoData from props.location.state. The problem is when I refresh the page, this photoData is cleared. This works well on the development mode, so the photoData is persisted even after I refresh the photos page. But it doesn't work in the production mode. I was thinking to store the data to redux store but this is over-killing.

Any idea to solve this issue?

Upvotes: 2

Views: 3110

Answers (4)

Jesse Winton
Jesse Winton

Reputation: 696

I had this same issue, and I ended up using a hook that persists the state in local storage. I don't know if you're using hooks, but assuming you are this should solve your problem:

import { useEffect, useState } from 'react';

export const usePersistState = (key: string | any, defaultValue: string | boolean | any) => {
  const [value, setValue] = useState(() => {
    if (typeof window !== 'undefined') {
      const persistedState = window.localStorage.getItem(key);
      return persistedState !== null ? JSON.parse(persistedState) : defaultValue;
    }
  });

  useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
};

This sets your state based on a localStorage item, so it should have a boolean value. Then import it into your components, and use it much like useState.

import { usePersistState } from 'hooks/use-persist-state';

const [state, setState] = usePersistState('localStorageKey', localStorageValue);

I've used this to persist data I'm calling from an API, and to show/hide a cookie consent banner, so it's got a lot of uses. Happy coding, hopefully this solves your problem!

Upvotes: 1

Vyk
Vyk

Reputation: 151

I ran the same problem. In my case it was because I was opening a new tab every time I accessed the link. One possible way to solve it is to use window.history.state (according to this solved issue: https://github.com/gatsbyjs/gatsby/issues/9091).

Upvotes: 2

Pa Ye
Pa Ye

Reputation: 1838

State is set during a transition between pages. In other words, it's passed from one page to another. When you refresh the target page, location.state will be null as state should come from the previous page.

Upvotes: 0

Owais Latif
Owais Latif

Reputation: 85

Put state in local storage state will definately lost if you refresh the page

Upvotes: 0

Related Questions