How to migrate from redux to react-query?

I started studying react-query, I can’t figure it out.
Please help with an example based on my code

There was such an action and a reducer

export const addHighlighting = parent_id => dispatch => {
  dispatch({
    type: types.HANDLE_COMMENT_HIGHLIGHTING,
    payload: {
      parent_id,
      is_highlighted: true
    }
  })
}

case types.HANDLE_COMMENT_HIGHLIGHTING:
      const parentIndex = state.comments.findIndex(
        comment => comment.id == action.payload.parent_id
      )
      return update(state, {
        comments: {
          [parentIndex]: {
            is_highlighted: { $set: action.payload.is_highlighted }
          }
        }
      })

there was functionality on the page that raised the status and, when hovering the mouse, highlighted the parent’s comment.

onMouseEnter={() => addHighlighting(comment.parent)}
onMouseLeave={() => removeHighlighting(comment.parent)}

How now to do also on react-query with mutation?

>Solution :

If you want to handle the highlighting status locally using React Query’s local state management, you can utilize the useQuery and useMutation hooks provided by React Query. Here’s an example of how you can achieve this:

Set up React Query in your application. Wrap your app or the relevant component with the QueryClientProvider and provide a queryClient instance:

import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app component */}
    </QueryClientProvider>
  );
}

Define a query key constant for your highlighting status:

const HIGHLIGHTING_STATUS_QUERY_KEY = 'highlightingStatus';

Create a component that will render the comments and handle the highlighting functionality:

import { useQuery, useMutation } from 'react-query';

function Comment({ comment }) {
  const { data: highlightingStatus } = useQuery(HIGHLIGHTING_STATUS_QUERY_KEY);

  const toggleHighlighting = useMutation((parentId) => {
    // Update the highlighting status locally based on the parentId
    // You can use the `mutate` function to update the local state
  });

  const handleMouseEnter = () => {
    toggleHighlighting.mutate(comment.parent, {
      onSuccess: () => {
        // Handle successful mutation (optional)
      },
    });
  };

  const handleMouseLeave = () => {
    // Implement the logic to remove highlighting if needed
  };

  const isHighlighted = highlightingStatus === comment.parent;

  return (
    <div
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      className={isHighlighted ? 'highlighted' : ''}
    >
    </div>
  );
}

Create a separate component to manage the highlighting status and mutation logic:

import { useQueryClient } from 'react-query';

function CommentList() {
  const queryClient = useQueryClient();

  const toggleHighlighting = useMutation((parentId) => {
    // Update the highlighting status locally based on the parentId
    // You can use the `mutate` function to update the local state
  }, {
    onSuccess: () => {
      // Invalidate the highlighting status query so it refetches the latest data
      queryClient.invalidateQueries(HIGHLIGHTING_STATUS_QUERY_KEY);
    },
  });

  // Fetch the highlighting status data
  const { data: highlightingStatus } = useQuery(HIGHLIGHTING_STATUS_QUERY_KEY);

  return (
    <>
      {/* Render your comment list */}
      {comments.map((comment) => (
        <Comment key={comment.id} comment={comment} />
      ))}
    </>
  );
}

The Comment component handles the highlighting functionality based on the local highlighting status obtained from the useQuery hook. The toggleHighlighting mutation function is used to update the local state, and upon a successful mutation, the highlighting status query is invalidated to refetch the latest data.

Remember to adjust the code according to your specific logic and requirements.

If this highlighting info is not saved on a server, React Query is the wrong lib for that job.

Stackblitz example URL: https://stackblitz.com/edit/react-wmkh8i?file=src/Comment.js

Leave a Reply