Home > OS >  Perform DOM operation after it was updated inside onMutate in react-query
Perform DOM operation after it was updated inside onMutate in react-query

Time:11-01

I wrote a component called Chat (some parts are omitted for simplicity):

function Chat() {
  const containerRef = React.useRef(null);
  const messages = useQuery({
    queryKey: ["messages"],
    queryFn: api.getMessages
  });
  
  const createMessage = useMutation({
    mutationFn: (message) => api.createMessage(message),
    onMutate: (message) => {
      // 1. cancels query, updates cache, returns previous value
      optimisitcUpdate(messages, message);

      // 2. scroll to bottom
      const { current: container } = containerRef;

      // ❌ won't work, because the DOM is not updated yet
      container?.scrollTo(0, container.scrollHeight);

      //            
  • Related