[React] axios 요청을 성공할 때까지 보내야 할 때

2023. 7. 22. 14:32React

다음 코드와 같이 setTimeout을 사용한다.

RETRY_DELAY_MS = 2000 // 2초마다 재송신

const func = () = {
const [ qnaList, setQNAList ] = useState( null );
const fetchData = () => {
    const body = {
      access_token: cookie.load( 'user' ).accessToken,
      history_id: historyId
    }
    axios.post( "http://localhost:8000/history/qna", body ).then( ( res ) => {
      console.log( res.data );
      const result = res.data
      if ( result.type ) { setQNAList( result.qnas ) }
      else { console.log( result.message ); setTimeout( fetchData, RETRY_DELAY_MS ) }

    } ).catch( error => {
      // 요청 중 에러가 발생했을 때 처리
      console.error( error );
    } )
  }
  useEffect( () => {
    fetchData();
  }, [] )
  
  return
  (
  )
  }