0

how do I call an API and store it in an atom?

The API needs a parameter from the component, so I use 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);

sourceDetailsStateData returns an empty object. How do I update it so I can get the response from the API? Please advice.

arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60
  • Does your API return an empty object? Using a `selectorFamily` is perfectly fine, why would you want to store it inside an `atom`? – Johannes Klauß Sep 30 '21 at 08:28
  • No it doesnt. The way we want it to work is, once I get the API data, I store it in an atom and display corresponding values in input fields. User can edit them and I will be sending the entire json with modified values back to the server using a post. – arunmmanoharan Sep 30 '21 at 16:56
  • Can you provide codesandbox? Otherwise it's very hard to help. The loading code itself looks good. Although if this is the way to want to work with, it would make more sense to load the data outside of recoil and just set the atom. Not quite sure why you'd need a selector for this just to load the data. – Johannes Klauß Oct 01 '21 at 09:40

0 Answers0