Tech/React

refetchQueries

kimjingyu 2023. 5. 12. 17:52
728x90

✏️ 정의

  • 기존에 받아왔던 데이터가 변경되었을 경우, 최신 데이터로 다시 fetch 해주기위해서 사용된다.
  • Apollo에서 제공하는 기본 기능이다.
  • useMutation 함수 안에 refetchQueries라는 키가 있다.
  • 모든 Mutation 이후에 refetchQuries를 사용하는 것은 아니다. Mutation 이후에 변경된 데이터를 받아올 수 없을 경우에 사용한다.

🔎 사용법

  • refetchQuries는 배열로 시작한다.
  • 그 안에 어떤 query를 하고, 그 query의 variables가 무엇인지 다시 설정해준다.
  • 그러면 Mutation이 성공적으로 끝났을 경우, refetchQueries를 실행시켜준다.
// 삭제 mutation -> refetchQueries를 이용해 최신 데이터 받아오기

const deleteBoard = async () => {
	try {
		const result = await deleteBoard({
			variables: {
				boardId: event.target.id,
			},
			refetchQueries: [
				{
					query: FETCH_BOARDS
				},
			]
		});
	} catch (error) {
		console.log(error);
	}
};
refetchQueries: [{ query : FETCH_BOARDS,
                   variables : { 기존의 fetch때 보내준 것} }]

 

인용

https://www.apollographql.com/docs/react/data/mutations/

 

Mutations in Apollo Client

Modify data with the useMutation hook

www.apollographql.com

https://www.apollographql.com/blog/apollo-client/caching/when-to-use-refetch-queries/

 

When To Use Refetch Queries in Apollo Client

One of the most common use cases front-end developers face is re-render the UI after executing a mutation and changing something in the backend. To solve this problem, a lot of developers like to use the refetchQueries API. For example, if I wanted to add

www.apollographql.com

 

728x90