blitz-js / legacy-framework

MIT License
3 stars 2 forks source link

Custom API request helper function #38

Open anteprimorac opened 3 years ago

anteprimorac commented 3 years ago

What do you want and why?

Simplify requests to custom api routes that use blitz session middleware.

import { getAntiCSRFToken } from "blitz";

const antiCSRFToken = getAntiCSRFToken();
​
window.fetch("/api/custom", {
  credentials: "include",
  method: "POST",
  body: JSON.stringify(data),
  headers: { "Content-Type": "application/json", "anti-csrf": antiCSRFToken },
});

Possible implementation(s)

import { fetchWithCredentials } from 'blitz';

fetchWithCredentials("/api/custom", {
  method: "POST",
  body: JSON.stringify(data),
  headers: { "Content-Type": "application/json" },
});
reiwa commented 3 years ago

Blitz.js use ReactQuery inside useMutation, but this function doesn't allow normal functions.

import { useMutation } from 'blitz';

const antiCSRFToken = getAntiCSRFToken();

const [customMutation] = useMutation(() => { // ERROR!
  return window.fetch("/api/custom", {
    credentials: "include",
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json", "anti-csrf": antiCSRFToken },
  });
})

because of this line: https://github.com/blitz-js/blitz/blob/654d9378adb985372cdf49729be3b8cf66f7d62a/packages/core/src/utils/react-query-utils.ts#L53

Is it possible to merge useReactQueryMutation and Blitz's useMutation ?

import { useMutation } from "blitz"

const mutation = useMutation(body => {
  return window.fetch("/api/custom", {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
})

like this:

try {
  const enhancedResolverRpcClient = sanitize(mutationResolver)

  return useReactQueryMutation(
    (variables: TVariables) => enhancedResolverRpcClient(variables, {fromQueryHook: true}),
    {
      throwOnError: true,
      ...config,
    } as any,
  ) as MutationResultPair<TResult, TError, TVariables, TSnapshot>
} catch (error) {
  // ReactQuery
}

https://github.com/blitz-js/blitz/blob/654d9378adb985372cdf49729be3b8cf66f7d62a/packages/core/src/use-mutation.ts#L14

flybayer commented 3 years ago

@reiwa can't do that because we can't calculate a query key for that. For using a regular function, you need to use the hook directly from react-query: import {useMutation} from 'react-query'