[React + NEXT.JS Study] useSWR mutate 란?

JooSehyun·2023년 4월 17일
0

[Study]

목록 보기
13/32
post-thumbnail

React + NEXT.JS Study

useSWR mutate 란?

useSWR 이란?


SWR is a React Hooks library for remote data fetching.

The name “ SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by RFC 5861.

SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.


마지막 줄을 보면 맨처음 cache로 부터 받아온 데이터 즉 오래된 정보를 먼저 리턴을 해주고 그 다음 fetch를 한다음 마지막으로 업데이트된 데이터를 다시 리턴한다.

useSWR의 mutate 함수

SWR을 이용해 데이터를 가져오는 작업을 진행하고. 만약 가져온 데이터를 변경해야한다면 어떻게 해야 할까? SWRmutate라는 함수를 제공함으로 인해 데이터를 변경할 수 있도록 제공한다.
캐시 된 데이터를 갱신하기 위한 함수이다.

useSWRConfig( ) hook으로 부터 mutate함수를 얻을 수 있으며, mutate(key)를 호출하여 동일한 키를 사용하는 다른 SWR hook에게 갱신 메시지를 전역으로 브로드캐시팅할 수 있다.

예제) 포스트의 댓글을 한번 생성해보자

현재 내가 만들고 있는 커뮤니티의 포스트 댓글 기능을 구현하는데 새로고침을 해야 댓글이 나타난다. 어떻게 하는지 보자.


기존 댓글 기능 방식

const { data: comments } = useSWR<Comment[]>(
        identifier && slug ? `/posts/${identifier}/${slug}/comments` : null
    );
const handleSubmit = async (e: FormEvent) => {
  	e.preventDefault();
  	if(newComment.trim() === ""){
    	return;
  	}
  	try {
    	await axios.post(`/posts/${post?.identifier}/${post?.slug}/comments`,{
  			body: newComment
	});
    setNewComment("");
	} catch (error) {
  	console.log(error);
	}
}


댓글작성 버튼을 누르면 바로 댓글이 나타나야하는데 새로고침을 해야 나타나고 있다.


mutate함수 적용 후 댓글 기능 방식

const { data: comments, 👉mutate👈 } = useSWR<Comment[]>(
        identifier && slug ? `/posts/${identifier}/${slug}/comments` : null
    );
const handleSubmit = async (e: FormEvent) => {
  	e.preventDefault();
  	if(newComment.trim() === ""){
    	return;
  	}
  	try {
    	await axios.post(`/posts/${post?.identifier}/${post?.slug}/comments`,{
  			body: newComment
	});
	👉mutate();👈
    setNewComment("");
	} catch (error) {
  	console.log(error);
	}
}

mutate를 추가하여 댓글작성 버튼을 누르면 바로 댓글이 나타난다.

mutate를 사용하고 댓글작성 버튼을 누르면 한번 더 캐싱된 값을 업데이트를 해준다.


mutate 중복 에러

예제)

const { data: post, error, mutate } = .... 
const { data: comments, mutate } = ....

이렇게 두개의 변수에 mutate가 있다면 mutate가 중복되는 에러가 발생된다.

*Can not redeclare block-scoped variable 'mutate' 로 뜬다.

*the name mutate is defined multiple times 로 뜬다.

이럴 때는 Destructuring 할 때 상수명을 다르게 해 주면 된다.

예제)

const { data: post, error, mutate:postmutate } = .... 
const { data: comments, mutate:commentmutate } = ....

이렇게 mutate: 이름으로 만들고 각 함수에 mutate( );로 호출했던 것을 각 이름으로 바꿔서 호출해 준다.

예 : mutate( ); => postmutate( ); , commentmutate( );


0개의 댓글