0

How do I update existing records by their index key?

Im not so familiar with React Query.

When a button is clicked, then this will trigger onClickHandler to update the object value by its index key.

import {useQuery, useQueryClient} from '@tanstack/react-query';

const {
  data: comments,
  isError,
  isLoading
} = useQuery({
      queryKey: ['comments'],
      queryFn: async () => {
         const response = await fetch(`https://jsonplaceholder.typicode.com/posts/1/comments`);
         return response.json();
      }
});

const onClickHandler = (index) => {
   const previousData = queryClient.getQueriesData(['comments']);

   queryClient.setQueryData(['comments'], (comments) => {

      comments.map((r, i) => {

         r['is_shown'] = false;
       
         if(i === index) {
            r['is_shown'] = true;
         }

         return r;

      });

   });
};

1 Answer 1

0

you forgot to return the new data inside setQueryData function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.