React Umi umi-request useRequest

api-service

api: src/services/ant-design-pro/api.ts

export async function getCurrentTime(options?: { [key: string]: any }) {
  return request<{ id?: number }>('/dev_time', {
    method: 'GET',
    ...(options || {}),
  });
}

api-dev-proxy

proxy: forward all dev* to localhost

export default {
  dev: {
    '/api/': {
      target: 'https://preview.pro.ant.design',
      changeOrigin: true,
    },
    '/dev*': {
      target: 'http://localhost:8801',
      changeOrigin: true,
    },
  }
}

use-api-service

by url

  const { data, error, loading, run } = useRequest(
       {
           url:'https://time.apple.com'
       }, 
       {
          formatResult: res => res?.time
       }
  );

by auto-open-api

const { data, loading, run } = useRequest(services.api.getCurrentTime);

or

const { data, loading, run } = useRequest(services.api.getCurrentTime, 
       {
          formatResult: res => res?.time
       }
);

ui-state

import { useRequest } from 'umi';
import {useEffect, useState} from 'react';

import services from '@/services/ant-design-pro';

export default () => {
  const [index, setIndex] = useState(0);
  const [homeConfig, setHomeConfig] = useState('');

  const { data, loading, run } = useRequest(services.api.getCurrentTime);

  useEffect(() => {
    setIndex(index+1)
    setHomeConfig("data="+JSON.stringify(data))
  }, [data]);

  return (
    <div>
      <button onClick={()->run()}>
        请求网络 {index}, {loading}
      </button>
      <h2>data={index + ':' + homeConfig}</h2>
    </div>
  );
};

show all response data from api

1: if the server response is formated by this, you don’t have to do anything

interface ErrorInfoStructure {
  success: boolean;
  data?: any;
  errorCode?: string;
  errorMessage?: string;
  showType?: ErrorShowType;
  traceId?: string;
  host?: string;
  [key: string]: any;
}

2:if the server response only string or other bean, you can parse by app.ts or any request

in a single request, add ‘ formatResult:res => res ‘ in useRequest

  const { loading, run } = useRequest(services.api.getCurrentTime, {
    formatResult:res => res,
    onSuccess:(respond, params)=>{
      setIndex(index + 1);
      setHomeConfig('data=' + JSON.stringify(respond));
    },
    onError:(e, params) =>{
      setIndex(index + 1);
      setHomeConfig('data=' + JSON.stringify(params));
    }
  });

format all response request, add ‘middleware’ in app.ts

import { RequestConfig } from 'umi';
import { Context } from 'umi-request';

const IntbirdMiddleware = async (ctx: Context, next: () => void) => {
  await next();

  const respond = ctx.res
  ctx.res = {data: respond}
};

export const request: RequestConfig = {
  errorConfig: {
    adaptor: (resData, ctx) => {
      console.log('request.errorConfig.adaptor.resData: ' + JSON.stringify(resData));
      return {
        ...resData,
        errorMessage: 'intbird:'+resData.errorMessage,
      };
    },
  },
   middlewares: [IntbirdMiddleware],
};

3, Q: why errorConfig.adaptor notwork

A: formatResult in OptionsWithFormat, errorConfig.adaptor in BaseOptions