#window is undefined

8 messages · Page 1 of 1 (latest)

wide patrol
#

I am trying to check if window is undefined but how do I goddamn do it if the Node refuses to read the value of window at all?

let localStorageValue: undefined | {} = undefined 
    if (window !== undefined) /* qwik error: window is undefined */ {
      localStorageValue = JSON.parse(localStorage.getItem(`ctx_${key}`) ?? '')
    }
    const store = useStore(localStorageValue ?? value)
#

this function is called on a component$ root.tsx

function provideGlobalContext() {
  Object.entries(contexts).forEach(([key, value]) => {
    ctxIds.set(key as keyof typeof contexts, createContextId<typeof contexts[keyof typeof contexts]>(key))
    let localStorageValue: undefined | {} = undefined 
    if (window !== undefined) {
      localStorageValue = JSON.parse(localStorage.getItem(`ctx_${key}`) ?? '')
    }
    const store = useStore(localStorageValue ?? value)
    useContextProvider(ctxIds.get(key as keyof typeof contexts)!, store)
    useVisibleTask$(({ track }) => {
      Object.entries(store).forEach(([key,]) => {
        track(() => store[key as keyof typeof store])
      })
      localStorage.setItem(`ctx_${key}`, JSON.stringify(value))
    })
  })
}
karmic rose
#

From where do you call this method?

#

You should call it from the useVisibleTask$ life cycle method as this assures you are in in the browser.

wide patrol
#

oh

#

yes that solves the problem but I am still wondering why I cannot check if window variable is undefined

#

it is in fact undefined because it's ssr

#

but why can I not check it lmao