如何使用react和zustand存储向用户显示错误

问题描述 投票:0回答:1

我有以下问题。我应该如何向使用 zustand 存储数据的用户显示错误?我有一个函数

showError
,我通过我的 React 应用程序使用它来显示错误。这个想法是我传递一条错误消息并向用户显示一个祝酒词。

ItemsStore.ts

        try {
            const currentItem = await getItem(itemId);
            set(state => {
               state.items = [...state.items, currentItem]
            });
        } catch (error){
            // Example error: Item doesn't exist.
            // How to show my error to the user
            // I can't use my showError function here,
            // it should be inside a component to not
            // break the rules of hooks
        }
const MyComponent = () => {
   const items = useItemStore(state=>state.items);
   // I don't have an access what happens intern in my store
   // If error occurs the items are an empty array.
}
reactjs react-hooks zustand
1个回答
3
投票

在我的 Zustand 项目中,我创建了一个全局错误存储。

const setError = (set) => ({scope, errorMsg}) => {
  return set(state => ({
    ...state,
    error: {
      ...state.error,
      [`${scope}Error`]: errorMsg,
    }
  })}

我在函数的 catch 块中添加 setError :

 try {
    const currentItem = await getItem(itemId);
    set(state => {
        state.items = [...state.items, currentItem]
    });
} catch (error) {
    const {
        setError
    } = get().error
    // I often use function names as scopes
    setError("fnName", error.message)
}

然后我可以像这样访问组件中的错误消息:

const MyComponent = () => {
   const items = useItemStore(state=>state.items);
   const fnNameError = useItemStore(state=>state.error.fnNameError);
   
}
© www.soinside.com 2019 - 2024. All rights reserved.