最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use local or session storages in next js - Stack Overflow

programmeradmin4浏览0评论

I'm trying to set item to session storage when i get response from my ssr app, but it shows error that session storage is not defined, because in server side there is no storages like that, there is only cookie but I don't need that.

So my question is how can I set items to sessionsStorage from getInitialProps in NextJS

I'm trying to set item to session storage when i get response from my ssr app, but it shows error that session storage is not defined, because in server side there is no storages like that, there is only cookie but I don't need that.

So my question is how can I set items to sessionsStorage from getInitialProps in NextJS

Share Improve this question asked Feb 2, 2021 at 11:41 VahanVahan 1821 gold badge1 silver badge6 bronze badges 1
  • dev.to/devlargs/… looks really good. – Ryan Commented May 10, 2022 at 17:33
Add a comment  | 

3 Answers 3

Reset to default 9

I've created a custom hook for this to avoid SSR errors. The code inside the useEffect hook will be executed on client side only so you do not need to check window.

hooks/useSessionStorage.js

import { useState, useEffect } from "react";

const useSessionStorage = (name) => {
  const [value, setValue] = useState('')

  useEffect(() => {
    setValue(sessionStorage.getItem(name))
  }, [])

  return value
}

export default useSessionStorage

SomeComponent.js

import useSessionStorage from '../hooks/useSessionStorage'

const SomeComponent = () => {
  const zipCode = useSessionStorage('zipCode')

  return (
    <input value={zipCode} />
  )
}

getInitialProps would be executed in client-side or in server-side. So, you need to prevent access sessionStorage in server-side.

Page.getInitialProps = async (context) => {
  if (typeof window !== 'undefined') {
    window.sessionStorage.set('item', 'itemValue')
  }
}

You can not set items to sessionsStorage when calling getInitialProps, because getInitialProps runs on the server side.

When calling a method of the window object, you can first determine whether the window object is undefined.

If you use hooks:

useEffect(() => {
    if (window) { 
      // set props data to session storage or local storage  
    }
}, []);
发布评论

评论列表(0)

  1. 暂无评论