Enhancing User Experience with Daxus
Tags: showdev, react, webdev, javascript
Published: 2023-07-29 10:28:48

[Daxus](https://github.com/jason89521/daxus) is an exceptional server state management library tailored for React applications. With Daxus, developers have complete control over their data, allowing them to craft websites with superior user experiences.

## Building a Better User Experience with Daxus

Let's consider the scenario of developing a forum website. Our website comprises various lists of posts, such as "popular," "latest," "recommended," and more. Users can interact with the posts, for example, by liking them, and the post will display the total number of likes.

Initially, we might opt for React Query to manage the server data. Here's an example of how we could use React Query:

```ts
import { useQuery, useInfiniteQuery } from '@tanstack/react-query';

export function usePost(id: number) {
  return useQuery({
    queryKey: ['post', 'detail', id],
    queryFn: () => axios.get(`/api/post/${id}`)
  });
}

export function usePostList({ forumId, filter }: { forumId: string; filter: 'popular' | 'latest' | 'recommended' }) {
  return useInfiniteQuery({
    queryKey: ['post', 'list', forumId, filter],
    queryFn: ({ pageParam = 0 }) => axios.get(`/api/post?page=${pageParam}&forumId=${forumId}&filter=${filter}`),
    getNextPageParam: (lastPage, pages) => lastPage.nextCursor
  });
}
```

React Query provides the `useQuery` and `useInfiniteQuery` hooks to simplify data handling. With just the `queryKey` and `queryFn`, React Query efficiently manages the data for us.

Now, let's address the logic of users liking a post:

```ts
import { useMutation, useQueryClient } from '@tanstack/react-query';

export function useLikePost(id: number) {
  const client = useQueryClient();

  return useMutation({
    mutationFn: () => {
      return likePostApi({ id });
    },
    onSuccess: () => {
      client.invalidateQueries({ queryKey: ['post'] });
    }
  });
}
```

When a user likes a post, we invalidate all post data, triggering a refetch of the post the user is currently viewing. Moreover, when the user returns to the post list, it is also refetched, displaying the updated like count.

However, there is a noticeable delay between the user liking a post and the post displaying the updated like count. To address this in the post view, we can implement optimistic updates:

```ts
export function useLikePost(id: number) {
  const client = useQueryClient();

  return useMutation({
    mutationFn: () => {
      return likePostApi({ id });
    },
    onMutate: async () => {
      await client.cancelQueries({ queryKey: ['post', 'detail', id] });
      client.setQueryData(['post', 'detail', id], (old) => ({ ...old, likeCount: old.likeCount + 1 }));
    },
    onError: () => {
      client.setQueryData(['post', 'detail', id], (old) => ({ ...old, likeCount: old.likeCount - 1 }));
    },
    onSettled: () => {
      client.invalidateQueries({ queryKey: ['post'] });
    }
  });
}
```

Now, users can immediately see the result after liking a post. However, when they return to the post list, they still see the old post data. They have to wait for some delay to see the latest result. Considering the multiple lists on our website, finding the post in every list and then performing an optimistic update isn't efficient.

## Daxus to the Rescue!

Enter Daxus! With Daxus, we can create a custom data structure for our post data, ensuring that each post entity references the same data. This feature allows us to eliminate the delay issue without any hassle. Let's see how we can use Daxus to manage the post data:

```ts
import { createDatabase, createPaginationAdapter, useAccessor } from 'daxus';

export const database = createDatabase();

export const postAdapter = createPaginationAdapter<Post>();

export const postModel = database.createModel({name: 'post', initialState: postAdapter.initialState});

export const getPost = postModel.defineAccessor({
    name: 'getPost',
    async fetchData(id: number) {
        return axios.get(`/api/post/${id}`);
    },
    syncState( draft, { data } ) {
        postAdapter.upsertOne(draft, data);
    }
})

export const listPost = postModel.defineInfiniteAccessor({
    name: 'listPost',
    async fetchData({forumId, filter}: {forumId: string, filter: 'popular' | 'latest' | 'recommended'}, {previousData}) {
        const page = previousData?.nextCursor ?? 0;
        return axios.get(`/api/post?page=${page}&forumId=${forumId}&filter=${filter}`);
    },
    syncState( draft, { data, arg: { forumId, filter} }) {
        const key = `${forumId}&${filter}`;
        postAdapter.appendPagination(draft, key, data);
    }
})

export function usePost(id: number) {
    return useAccessor(getPost(id), state => postAdapter.tryReadOne(state, id));
}

export function usePostList({forumId, filter}: {forumId: string, filter: 'popular' | 'latest' | 'recommended'}) {
    return useAccessor(listPost({forumId, filter}), state => {
        const key = `${forumId}&${filter}`;
        return postAdapter.tryReadPagination(state, key)?.items
    });
}

export async function likePost(id: number) {
    postModel.mutate(draft => {
        postAdapter.readOne(draft, id).likeCount += 1;
    })
    
    try {
        await likePostApi({id});
    } catch {
        postModel.mutate(draft => {
            postAdapter.readOne(draft, id).likeCount -= 1;
        })
    } finally {
        postModel.invalidate();
    }
}
```

In Daxus, we provide the necessary instructions on how to update our state after fetching the data from the server. The `createPaginationAdapter` function returns an object with operations for accessing pagination data. If we need a more customizable data structure, we can build our adapter as well.

Since each entity in the pagination data structure references the same data, when a user likes a post and returns to any list, they will immediately see whether they have liked that post. No delays, no fuss - just a seamless user experience!

For more detailed information and code examples, please visit the [Daxus GitHub repository](https://github.com/jason89521/daxus).

> Daxus is continually evolving, and your valuable feedback is crucial to making it even better! Give Daxus a try and share your thoughts with us! Let's create remarkable React applications together!