0

my project is on nextjs. before return, I need localStorage or window. but it gives me the Error localStorage is not defined and window is not defined... I have checked other questions but there is no proper answer. Please someone can help me to fixes this issue. Here is code:

enter image description here enter image description here

import moment from "moment";
import { useState } from "react";



export default function Clicked() {

    const [passed, setPassed] = useState(false)

    const click = () => {
        const currentTime =moment().format('HH:mm:ss');


        
        var endTime = moment().add(10, 'second').format('hh:mm:ss A')
        
        localStorage.setItem('currentTime', currentTime)
        localStorage.setItem('endTime', endTime)
        
        
        
        console.log(endTime)
        console.log(currentTime)
        
        
    }
    console.log(window)
    const currentTime = localStorage.getItem("currentTime");
    console.log('currentTime', currentTime)


    return(
        <>
        
            <button onClick={() => click()}>click</button>
            <h1>hello</h1>
        </>
    )
}
Shahab Khan
  • 929
  • 1
  • 10
  • 17
  • 2
    Does this answer your question https://stackoverflow.com/a/59403018/16732460 – iunfixit Aug 26 '21 at 12:55
  • No, I am using react hooks. – Shahab Khan Aug 26 '21 at 12:57
  • 1
    @ShahabKhan Just scroll that thread, it has answer for hooks too: https://stackoverflow.com/a/59403018/11613622 -- basically the (three) statements that you have written after the `click` function need to be moved to a `useEffect` hook. Alternatively you can just check if `typeof window !== 'undefined'` before executing your client side code. That too is mentioned in that thread. – brc-dd Aug 26 '21 at 13:17
  • Yes, Thank you... – Shahab Khan Aug 26 '21 at 13:29

0 Answers0