英文:
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,
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论