에러 처리

Loading preview…
1import useSWR from 'swr'2import { useState } from 'react'3import '../styles.css'45async function fetcher([key, shouldFail]) {6  await new Promise((resolve) => setTimeout(resolve, 800))7  if (shouldFail) throw new Error('The simulated request failed. Try again!')8  return { message: 'Data loaded successfully.' }9}1011export default function App() {12  const [shouldFail, setShouldFail] = useState(true)13  const { data, error, isLoading, isValidating, mutate } = useSWR(14    ['message', shouldFail], fetcher, { shouldRetryOnError: false }15  )1617  return (18    <main>19      <h1>Error handling</h1>20      <p>This fetcher simulates a slow request that can fail.</p>21      <label>22        <input type="checkbox" checked={shouldFail}23          onChange={(event) => setShouldFail(event.target.checked)} />24        Fail the request25      </label>26      {isLoading && <p>Loading…</p>}27      {error && <p role="alert">{error.message}</p>}28      {data && <p>{data.message}</p>}29      <button onClick={() => mutate()} disabled={isValidating}>Retry</button>30    </main>31  )32}