Search code examples
react-query

How to access the data from a mutate within a separate component in react-query?


This is my placeholder codesandbox example https://codesandbox.io/s/elastic-feistel-n7qkgt?file=/components/App.tsx

It is possible to access the data from multiple 'useQuery' methods in different components referencing the same queryKey.

I want to know how you would access the queryKey from a mutate method, in a separate component to pull the 'success', 'error', 'data' etc.

Component which mutates

import React, { useState, useRef } from "react";

import "./App.scss";

import { postNutritionix } from "../apis/postNutritionix";
import { useMutation } from "@tanstack/react-query";

const CompPostGetData = () => {
  const refQuery = useRef(null);
  const refApiId = useRef(null);
  const refApiKey = useRef(null);

  const { error: errorMutate, mutate, data: respMutate } = useMutation({
    mutationFn: postNutritionix,
    onSuccess: (resp) => {
      console.log(resp);
    }
  });

  const handleSubmitQuery = (evt) => {
    mutate({
      apiId: refApiId.current.value,
      apiKey: refApiKey.current.value,
      query: refQuery.current.value
    });
    evt.preventDefault();
  };

  const errorMessage = errorMutate?.response?.data?.message;

  const foodNutrients = respMutate?.data?.foods?.[0] || {};

  console.log(foodNutrients);
  return (
    <section>
      <article>
        <form onSubmit={handleSubmitQuery}>
          <ul>
            <li>
              <label>
                Food: <input type="text" ref={refQuery} />
              </label>
            </li>
            <li>
              <label>
                apiId:
                <input type="password" ref={refApiId} />
              </label>
            </li>
            <li>
              <label>
                apiKey:
                <input type="password" ref={refApiKey} />
              </label>
            </li>
          </ul>
          <button type="submit">Submit query</button>

          {errorMutate ? (
            <div className={"error"}>Error: {errorMessage}</div>
          ) : null}
        </form>
      </article>
    </section>
  );
};

component which consumes data from mutate

const CompGetFromMutateData = () => {
  // How to get data from the mutate determined from other component
  // const {data} = useMutation({
  // queryKey here???
  // });
};

Solution

  • ok I've found a github issue that address it with alternatives. https://github.com/TanStack/query/issues/2304

    Updated my example 1 using additional context to wrap mutation: https://codesandbox.io/s/elastic-feistel-n7qkgt?file=/components/withMutationProvider.tsx

    updated example 2: More elegant solution - subscribing to the mutation https://codesandbox.io/s/infallible-phoebe-t8zgdj