1

I have a todo app, and I have an issue that I receive the old todo instead of the updated one.

after saving a todo, I'm opening a modal with the todo info

but instead of showing the updated todo, it's showing the previous todo.

here is the modal related code (the modal itself is from a different repo):

const {todo} = useTodoQuery()

const openModal = () => modal.open(todo)

return (
   <TodoModalButton onClick={openModal}>Open Todo Preview Modal</TodoModalButton>
)

here is how I fetch the todo with react-query

const useTodoQuery = () => {
  const {data, ...rest} = useQuery(['todo', todoId], async () => {
    if (todoId) {
      return await getTodo(todoId)
    }
    return null;
  })

  return {data, ...rest}
}

here is how I start the react query client:

const queryClient = new QueryClient({
  defaultOptions: {
    suspense: false,
  }
})

I've tried putting in inside the base wrapper, and outside of the app, same results

and here is how I'm updating to todo with react query:

const useUpdateTodo = () => {
 const todoMutation = useMutation(
    ['todo'],
    getUpdatedTodo,
    {onSuccess: () => queryClient.invalidateQueries(['todo', todoId])}
  );

 const updateTodo = (todo) => todoMutation.mutateAsync(todo)

 return {updateTodo}
}

when I do : await updateTodo(todo) and click on the openModal() button / call the openModal() function the modal is opened with the previous todo.

what could be the issue?

noer
  • 35
  • 3
  • Are you sure you are actually updating the todo on the server? Inside your `useMutation()`, the mutation function is a GET (`getUpdatedTodo`). I'd expect that to be a POST or PUT or something like that. – Ro Milton Jul 19 '23 at 06:26

1 Answers1

0

It seems that when you call openModal, the todo is not updated immediately and it is set with the previous value. It is better to open the medal after receiving the todo.

const useUpdateTodo = () => {
      const todoMutation = useMutation(
        ['todo'],
        getUpdatedTodo,
        {
          onSuccess: () => {
            queryClient.invalidateQueries(['todo', todoId]);
            openModal();
          }
        }
      );
    
      const updateTodo = (todo) => todoMutation.mutateAsync(todo);
    
      return { updateTodo };
    };

and :

const openModal = (updatedTodo) => modal.open(updatedTodo);
zahra zamani
  • 1,323
  • 10
  • 27