TanStackT
TanStack2w ago
7 replies
dual-salmon

How to make isomorphicFn generic?

title pretty much. The first works, but I would like to make it generic so it returns correct types (mostly for string based enums)

the lower one is my current workaround

export const getLocalStorage = createIsomorphicFn()
  .client((key: string, defaultValue: string) => {
    const item = window.localStorage.getItem(key);

    if (item) {
      console.log("found in localstroage, returning", item)
      return JSON.parse(item);
    }
    else {
      console.log("not found in local storage, returning default", defaultValue)
      return defaultValue;

    }
  })
  .server((key: string, defaultValue: string) => {
    console.log("running on server, returning default", defaultValue)
    return defaultValue;
  })


export function getLocalStorage<T>(key: string, defaultValue: T): T {
  if (typeof window !== 'undefined') {
    const item = window.localStorage.getItem(key);

    if (item) {
      console.log("found in localstroage, returning", item)
      return JSON.parse(item);
    }
    else {
      console.log("not found in local storage, returning default", defaultValue)
      return defaultValue;
    }
  }
  else {
    console.log("running on server, returning default", defaultValue)
    return defaultValue;
  }
}
Was this page helpful?