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
3 Answers
Reset to default 9I'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
}
}, []);