How to handle multiple errors in a zustand store

26 views Asked by At

I'm using zustand for a React Native project, and I was wondering what's the best practise to handle errors while having multiple actions in the same store. My store looks something like this:

type PostStore = {
  posts: Post[];
  fetchPosts: () => Promise<Post[]>;
  addNewPost: (post: Post) => Promise<Post>;
};

export const usePostStore = create<PostStore>((set) => ({
  posts: [],
  fetchPosts: async () => {
    try {
      {/* async call #1 happens here */}
    } catch (err: unknown) {
      {/* setting error state #1 */}
    }
  },
  addNewPost: async (post: Post) => {
    try {
      {/* async call #2 happens here */}
    } catch (err: unknown) {
      {/* setting error state #2 */}
    }
  },
}));

How should I store the error state of both async calls?

I can obviously add an error state in the store for both functions (something like fetchPostsError and addNewPostError), but it's not a really scalable solution.

0

There are 0 answers