0

如何调用 API 并将其存储在 atom 中?

API 需要来自组件的参数,所以我使用 selectorFamily。

import { atom, atomFamily, selector, selectorFamily } from 'recoil';
import { load } from '../../services/config';
import { convertTableDataMapToArray } from '../../components/SourceLoader/util';
import { ISourceConfigurationEdit } from '../../components/SourceLoader/types';

export const getSourceDetails = selectorFamily({
  key: 'SourceLoaderSourceDetails',
  get: (id: number) => async () => {
    try {
      const { data } = await load(`/sourceloader/getSourceDetails/${id}`);
      return convertTableDataMapToArray(data);
    } catch (e) {
      console.error(e);
    }
  },
  set:
    () =>
    ({ get, set }, newValue) => {
      set(sourceDetailsState, { ...get(sourceDetailsState) });
    },
});

export const sourceDetailsState = atom<Partial<ISourceConfigurationEdit>>({
  key: 'getSourceDetailsState',
  default: {},
});


const sourceDetailsData = useRecoilValue(
  getSourceDetails(sourceLoaderData.id as number),
);

const [sourceDetailsStateData, setData] = useRecoilState(sourceDetailsState);

console.log('sourceDetailsStateData', sourceDetailsStateData);

sourceDetailsS​​tateData 返回一个空对象。如何更新它以便从 API 获得响应?请指教。

4

0 回答 0