#[SOLVED] window is not defined

32 messages · Page 1 of 1 (latest)

urban epoch
#

Hi, im using window.localStorage in my project, website is working properly but terminal throws this error every compiling, tried suggestion "use if (window !== undefined)" but its not working, it just now throws "window is not defined" with pointing this line instead of original one

spring girderBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

robust scarab
#

Window is only available inside client

urban epoch
#

guess im using client component

robust scarab
#

yes

robust scarab
#

pls share code snippet if so

urban epoch
# robust scarab still undefined?

yep


export const StableDiffusionTab = forwardRef<Props, "div">(({setModalImage, modalState}, ref) => {

    const fetchJobs = () => {
        // @ts-ignore
            const jobs = window.localStorage.getItem("jobList")
            if (jobs !== 'null' && jobs !== null) {
                console.log(jobs)
                return JSON.parse(jobs)
            } else {

                return []
            }
    }

error

⨯ src\app\tabs\stablediffusion.tsx (68:25) @ windowReferenceError: window is not defined
    at fetchJobs (./src/app/tabs/stablediffusion.tsx:48:22)
    at eval (./src/app/tabs/stablediffusion.tsx:70:80)
  66 |     const fetchJobs = () => {
  67 |         // @ts-ignore
> 68 |             const jobs = window.localStorage.getItem("jobList")
     |                         ^
  69 |             if (jobs !== 'null' && jobs !== null) {
  70 |                 console.log(jobs)
  71 |                 return JSON.parse(jobs)
robust scarab
#

can u share full component

#

a simple fix would be to check if window is undefined before setting

urban epoch
robust scarab
#

yep i see

#

ur calling window before it is available i think

#

i would

urban epoch
robust scarab
#
const [ jobList, setJobs ] = useState<Job[]>(fetchJobs());
#

change this to:

#
const [ jobList, setJobs ] = useState<Job[]>([]);
#

keep it empty

#

add useEffect()

#

and set state from useEffect

#

useEffect will call and window object shud be available

#
useEffect(() => {
  setJobs(fetchJobs());
}, []);
urban epoch
robust scarab
#

no problem

#

u can mark as solved 🙂

frank pecan
#

@robust scarab what message should I mark

urban epoch
#

[SOLVED] window is not defined