如何在reactJS中集成API

ymdaylpp  于 2023-01-18  发布在  React
关注(0)|答案(1)|浏览(171)

我有一个如下的API,

http:test.com/api/v1/getPriorityById/{priorityId}

使用端点数据,

export const useEndpointData = <TPath extends PathFor<'GET'>>(
    endpoint: TPath,  params?: OperationParams<'GET', MatchPathPattern<TPath>>,
    initialValue?:
    | Serialized<OperationResult<'GET', MatchPathPattern<TPath>>>
    | (() => Serialized<OperationResult<'GET', MatchPathPattern<TPath>>>),
    ): AsyncState<Serialized<OperationResult<'GET', MatchPathPattern<TPath>>>> & {
    reload: () => void;
} => {
    deprecationWarning({ endpoint, params, initialValue });
    const { resolve, reject, reset, ...state } = useAsyncState(initialValue);
    const dispatchToastMessage = useToastMessageDispatch();
    const getData = useEndpoint('GET', endpoint);

const fetchData = useCallback(() => {
    reset();
    getData(params as any)
        .then(resolve)
        .catch((error) => {
            console.error(error);
            dispatchToastMessage({
                type: 'error',
                message: error,
            });
            reject(error);
        });
}, [reset, getData, params, resolve, dispatchToastMessage, reject]);

useEffect(() => {
    fetchData();
}, [fetchData]);

  return {
    ...state,
    reload: fetchData,
  };
};

我在UI中集成如下,

const value = useEndpointData(`/v1/getPriorityById//${priorityId}`);

这里的问题是我有时会把priorityId设置为未定义,因此当priorityId未定义时,上面的API会重复抛出404错误。请任何人建议我如何在priorityId未定义时限制调用api。

1l5u6lss

1l5u6lss1#

您可以引入一个名为“shouldSkip”的新参数,或者如果您愿意,也可以只使用“skip”。
如果该值设置为true,则不初始化请求。

export const useEndpointData = <TPath extends PathFor<'GET'>>(
    endpoint: TPath,  params?: OperationParams<'GET', MatchPathPattern<TPath>>,
    shouldSkip = false,
    initialValue?:
    | Serialized<OperationResult<'GET', MatchPathPattern<TPath>>>
    | (() => Serialized<OperationResult<'GET', MatchPathPattern<TPath>>>),
    ): AsyncState<Serialized<OperationResult<'GET', MatchPathPattern<TPath>>>> & {
    reload: () => void;
}  => {
    deprecationWarning({ endpoint, params, initialValue });
    const { resolve, reject, reset, ...state } = useAsyncState(initialValue);
    const dispatchToastMessage = useToastMessageDispatch();
    const getData = useEndpoint('GET', endpoint);

const fetchData = useCallback(() => {
    if(shouldSkip) {
      return;
    }
    reset();
    getData(params as any)
        .then(resolve)
        .catch((error) => {
            console.error(error);
            dispatchToastMessage({
                type: 'error',
                message: error,
            });
            reject(error);
        });
}, [reset, getData, params, resolve, dispatchToastMessage, reject, shouldSkip]);

useEffect(() => {
    fetchData();
}, [fetchData]);

  return {
    ...state,
    reload: fetchData,
  };
};

const value = useEndpointData(`/v1/getPriorityById//${priorityId}`, priorityId === undefined);

相关问题