0

I have the following problem. How should I show an error to the user using a zustand for storing my data? I have a function showError that I am using through my react application to show an error. The idea is I pass an error message and a toast is shown to the user.

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.
}
Spongi
  • 501
  • 3
  • 10
  • 19

1 Answers1

2

In my Zustand project, I created a global error store.

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

You can call setError in your catch block:

 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)
}

Then you can access the error msg in your component

const MyComponent = () => {
   const items = useItemStore(state=>state.items);
   const fnNameError = useItemStore(state=>state.error.fnNameError);
   
}
Peter
  • 656
  • 1
  • 6
  • 14