velopert / react-tutorial

벨로퍼트와 함께하는 모던 리액트 튜토리얼 문서

Home Page:https://react.vlpt.us/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

4. react-async 로 요청 상태 관리하기 · GitBook

utterances-bot opened this issue · comments

4. react-async 로 요청 상태 관리하기 · GitBook

https://react.vlpt.us/integrate-api/04-react-async.html

react 18 upgrade 버전에서 해당 라이브러리가 제대로 동작하지 않는 것 같습니다. 해당 라이브러리의 github의 issue를 확인해본 결과 react 프로젝트에서<React.StrictMode /> 를 제거하면 동작하는 것 같습니다.

저도 윗분이랑 같은 경우였네요. 참고로 증상은 에러는 안나고 로딩중만 계속 뜹니다.
그건 그렇고 강의에 댓글창이 없는게 너무 불편하네요..

위에서 두 분 말씀하신 내용처럼 async-react는 현재(2022-)에 들어서는 사용하지 않는 것 같습니다. 대신 react-use에서 제공하는 useAsync, useAsyncRetry 함수 사용하여, 아래와 같이 코드 공유드립니다.

Users.js

import axios from 'axios'
import User from './User'
import React, { useState } from 'react'
import { useAsyncRetry } from 'react-use'

async function getUsers() {
  const url = 'https://jsonplaceholder.typicode.com/users'
  const response = await axios.get(url)
  return response.data
}

const Users = () => {
  const [userId, setUserId] = useState(null)
  const state = useAsyncRetry(getUsers)
  const { loading, error, value: users, retry } = state

  if (loading) return <div>로딩중..</div>
  if (error) return <div>Error Occured: {error.message}</div>
  if (!users) return <button onClick={retry}>불러오기</button>
  return (
    <>
      <ul>
        {users.map((user) => (
          <li
            key={user.id}
            onClick={() => setUserId(user.id)}
            style={{ cursor: 'pointer' }}
          >
            {user.username} ({user.name})
          </li>
        ))}
      </ul>
      <button onClick={retry}>again</button>
      {userId && <User id={userId} />}
    </>
  )
}

export default Users

User.js

import React from 'react'
import axios from 'axios'
import { useAsync } from 'react-use'

async function getUser(id) {
  const url = `https://jsonplaceholder.typicode.com/users/${id}`
  const response = await axios.get(url)
  return response.data
}

function User({ id }) {
  const state = useAsync(() => getUser(id), [id])
  const { loading, error, value: user } = state

  if (loading) return <div>로딩중..</div>
  if (error) return <div>Error Occured: {error.message}</div>
  if (!user) return null
  return (
    <div>
      <h2>{user.username}</h2>
      <p>
        <b>Email:</b> {user.email}
      </p>
    </div>
  )
}

export default User