Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6573

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T07:47:08+00:00 2024-11-27T07:47:08+00:00

Enhancing User Experience with Daxus

  • 60k

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:

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   }); } 
Enter fullscreen mode Exit fullscreen mode

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:

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'] });     }   }); } 
Enter fullscreen mode Exit fullscreen mode

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:

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'] });     }   }); } 
Enter fullscreen mode Exit fullscreen mode

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:

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();     } } 
Enter fullscreen mode Exit fullscreen mode

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.

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!

javascriptreactshowdevwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.