Skip to content

It doesn't work with NextJS and local/session Storage #2

@IsaacMujica

Description

@IsaacMujica

It doesn't work when you are using NextJS and try to access to local/session Storage through a custom hook.
The messages is:

Server Error
ReferenceError: sessionStorage is not defined

An example of the custom hook is the following:

const useAccountInitialState = () => {
  const [state, setState] = useState({
    account: {
      details: {}
    },
    accountStorage: () => ({})
  })
  const accountStorage: AccountStorage = useCallback((time = STORAGE_EXPIRE_DAYS) => ({
    details: JSON.stringify(localStorage.get('details'))
  }), [])

  const account: () => AccountInitialState = useCallback(() => ({
    details: accountStorage().details ?? {details: {}}
  }), [])

  useEffect(() => {
    setState({account, accountStorage})
  }, [])
  
  return state
}

I'm using:

  • NextJS v13.2.4
  • React v18.2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions