오원종
01/26/2021, 5:20 PM// /lib/apollo/queries/getAllSpots.ts
import { gql } from '@apollo/client';
import client from '~/lib/apollo/client';
const GET_ALL_SPOTS = gql`
{
getAllSpots {
id
// ...
y
}
}
`;
const getAllSpots = async (): Promise<GQL.GetAllSpots.Data> => {
const response = await client.query({
fetchPolicy: 'cache-first',
query: GET_ALL_SPOTS,
});
return response?.data?.getAllSpots;
};
export default getAllSpots;
그리고 상태는 recoil로 관리를 해 주려고 해서 상태를 관리하는 state 파일을 하나 다음과 같이 만들어서 spotList를 상태로 관리를 하고 첫 렌더링 시에 getAllSpots로 서버에서 데이터를 받아오는 작업을 하려고 합니다.
import { atom, selector, selectorFamily } from 'recoil';
import getAllSpots from '~/lib/apollo/queries/getAllSpots';
const spotsList: GQL.GetAllSpots.Data[] = [];
const query = selectorFamily({
key: 'query',
get: (first: boolean) => async () => {
try {
const res = await getAllSpots;
return res;
} catch (err) {
// TODO - ERROR
}
return null;
},
});
export const spotListQuery = selector({
key: 'spotListQuery',
get: ({ get }) => async () => {
const list = get(query(get(true)));
return list;
},
});
const spotListState = atom({
key: 'spotListState',
default: spotsList,
});
여기에서 궁금한 점은 1. state를 관리하는 위의 파일에서 graphql 쿼리를 어떻게 불러와야 하는지 이고 그 작업이 되고 나서 2. 해당 데이터가 필요한 컴포넌트에서 첫 렌더링 시에 graphql API 를 어떻게 trigger 해야 하는지 (위의 제 프로젝트에서는 getAllSpots를 첫 렌더링 시에 useEffect와 같은 훅으로 데이터를 불러와야 하는데 어떻게 그 작업을 trigger 해야 하는지) 가 궁금합니다… 제가 설명을 좀 충분하게 해드리지 못 했다면 스레드로 질문 주시면 추가적으로 설명 드리도록 하겠습니다! 감사합니다 ㅠㅠHyeseong Kim
01/26/2021, 5:25 PMHyeseong Kim
01/26/2021, 5:27 PM