
⇒ 컴포넌트가 지속적이고, 자동으로 데이터 업데이트 스트림을 받음, 빠르고 반응적인 UI
//npm
npm i swr
//yarn
yarn add swr
const fetcher = (...args) => fetch(...args).then(res => res.json())
// 함수 컴포넌트
import useSWR from 'swr'
function Profile() {
const {data, error, isLoading} = useSWR('/api/user/123', fetcher)
if (error) return <div>fail to load</div>
if (isLoading) return <div>Loading...</div>
//data rendering
return <div>hello{data.name}</div>
}
useSWR 훅을 사용해 데이터를 관리1st Argument: key, 2nd Argument: fetcher함수, 3rd Argument: options)isLoading, data, error 세 가지의 상태를 통해 요청의 상태 확인, 해당 UI반환data : fetcher가 이행한 키에 대한 데이터. 로드되지 않으면 undefinederror : fetcher가 던진 error. 로드되지 않으면 undefinedisLoading : 진행중인 요청 있고, 로드된 데이터가 없는 경우import axios from 'axios'
const fetcher = url => axios.get(url).then(res => res.data)
function App() {
const {data, error} = useSWR('/api/data', fetcher)
...
}
const {data} = useSWR(shouldFetch ? '/api/data' : null, fetcher)
const {data} = useSWR(() => shouldFetch ? '/api/data' :null, fetcher)
const {data} = useSWR(() => '/api/data?uid=' + userid, fetcher)
function MyProjects() {
const {data:user} = useSWR('/api/user')
const {data: projects} = useSWR(() => '/api/projects?uid=' + user.id)
if(!projects) return 'loading'
return projects.length
//세 가지 표현식은 모두 동일
useSWR('/api/user', () => fetcher('/api/user')
useSWR('/api/user', url => fetcher(url))
useSWR('/api/user', fetcher)
fetcher 함수에 여러 인자를 전달할 때 → 다중 인자를 포함하는 배열을 key 파라미터 사용가능const {data:user} = useSWR(['/api/user', token], ([url, token]) => fetchWithToken(url,token))
fetchWithUser(api,user) 함수가 있을 때 객체를 키로 바로 전달할 수 있고, fetcher가 그 객체를 받는다.//객체를 받고 또다른 인자로 전달하는 경우
const {data: user} = useSWR(['api/user',token], fetchWithToken)
const {data: orders} = useSWR(user ? ['/api/orders',user] : null, fetchWithUser)
//객체를 키로 바로 전달하고 fetcher가 그 객체를 받는 경우
const {data:orders} = useSWR({url:'/api/orders', args: user}, fetcher)
mutate ⇒ 데이터를 변경하거나 업데이트를 하는 동작을 수행하는 메서드//useSWRConfig Hook 사용하기(권장)
import {useSWRConfig} from "swr"
function App() {
const {mutate} = useSWRConfig()
mutate(key, data, options)
}
//전역으로 가져오기
import {mutate} from "swr"
function App() {
mutate(key, data, options)
}
Bound Mutate → 현재 키를 기반으로 데이트 변경, key 매개변수가 필요 없음
import useSWR from "swr"
function Profile() {
const {data, mutate} = useSWR('/api/user', fetcher)
return (
<div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
await requestUpdateUsername(newName)
mutate({...data, name: newName})
}}>Upeercase name</button>
</div>
}
}
mutate(key) 호출시 리소스에 대한 재검증 실시import useSWR, { useSWRConfig } from 'swr'
function App () {
const { mutate } = useSWRConfig()
return (
<div>
<Profile />
<button onClick={() => {
document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
// `/api/user` 라는 키를 가진 모든 SWR에게 재검증을 지시합니다.
mutate('/api/user')
}}>
Logout
</button>
</div>
)
}
useSWRMutation : 데이터 변경 작업을 비동기적으로 트리거하고, 결과를 처리import useSWRMutation from 'swr/mutation'
async function updateUser(url, {arg}: {arg: string}) {
await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${args}`
}
})
}
function Profile() {
const {trigger} = useSWRMutation('/api/user', updateUser, options)
return <button onClick={() => {
trigger('my_token')
})>UpdateUser</button>
}
useSWR('api/user', key=>{}) //key가 string으로 추론된다.
useSWR({a:'1', b:{c:'3',d:2}}, key=>{}) //key가 {a:string,b:{c:string,d: number}}
useSWR(['user',8], ([arg0, arg1]) => {}) //arg0: string, arg1: number로 추론
import useSWR, {Fetcher} from 'swr'
const uid='<user_id>'
const fetcher: Fetcher<User, string>= (id) => getUserById(id) //첫번째 매개변수 string, 반환타입 : user
const {data} : {data: User | undefined} = useSWR(uid, fetcher)
//타입 지정된 fetcher 사용
// getUser : (endpoint: string) => User
const {data} = useSWR('/api/user', getUser)
//데이터 타입 지정
const {data} = useSWR<User>('/api/user', fetcher)