使用Gatsby和Zustand-persist时遇到的问题?

huangapple go评论58阅读模式
英文:

Problems using localStorage with Gatsby & Zustand-persist?

问题

我在我的Gatsby应用中使用Zustand来管理全局状态,其中一个切片使用zustand-persist与本地存储同步。

我没有弄清楚是什么导致Gatsby开始出错(可能是更新了依赖项?),但现在当运行gatsby build时,我收到以下错误消息:
WebpackError: ReferenceError: localStorage is not defined

以下是我的代码:

import create from 'zustand';
import { configurePersist } from 'zustand-persist';

const { persist, purge } = configurePersist({
  storage: localStorage
})

我尝试了以下方法:

import { create } from 'zustand';
import { configurePersist } from 'zustand-persist';

const isBrowser = typeof window !== "undefined";

const { persist, purge } = configurePersist({
  storage: isBrowser ? window?.localStorage : null, // 在React Native中使用`AsyncStorage`
  // rootKey: 'root', // 可选项,默认值为'root'
})

但是我得到了以下错误:TypeError: Cannot read properties of null (reading 'getItem')

我是否需要实际模拟这些方法,以免破坏构建?是否没有用于处理这个问题的与Gatsby相关的包?

英文:

I am using Zustand in my Gatsby app to manage global state, one of my slices syncs with local storage using zustand-persist.
I didnt catch what caused Gatsby to start failing (maybe updated dependency?) but now i get the following error when running gatsby build:
WebpackError: ReferenceError: localStorage is not defined

Here is my code:

import create from 'zustand'
import { configurePersist } from 'zustand-persist';

const { persist, purge } = configurePersist({
  storage: localStorage
})

I tried:

import { create } from 'zustand'
import { configurePersist } from 'zustand-persist';

const isBrowser = typeof window !== "undefined";

const { persist, purge } = configurePersist({
  storage: isBrowser ? window?.localStorage : null, // use `AsyncStorage` in react native
  // rootKey: 'root', // optional, default value is `root`
})

But am getting this error: TypeError: Cannot read properties of null (reading 'getItem')

Do I need to actually mock these methods out so it doesnt break the build?
Is there no gatsby-specific package to handle this?

答案1

得分: 1

你可以像这样做,以便该函数仍然可用且不会报错,但它会返回null。

const isBrowser = typeof window !== "undefined";
const localStorage = isBrowser ? window.localStorage : {
  getItem: () => null,
}

const { persist, purge } = configurePersist({
  storage: localStorage,
});
英文:

You could do something like this so that the function is still available and wont error but it returns null.

const isBrowser = typeof window !== "undefined";
const localStorage = isBrowser ? window.localStorage : {
  getItem: () => null,
}

const { persist, purge } = configurePersist({
  storage: localStorage,
});

huangapple
  • 本文由 发表于 2023年7月7日 05:32:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定