리액트 컴포넌트에서 axios API 요청하기

파쏭쏭계란빡 ㅣ 2023. 8. 24. 00:04

axios

axios 설치

yarn add axios

npm i axios

get

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

post

axios.post("url", {
        firstName: 'Fred',
        lastName: 'Flintstone'
    })
    .then(function (response) {
        // response  
    }).catch(function (error) {
        // 오류발생시 실행
    })

delete

axios.delete('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })

put

axios.put("url", {
        username: "",
        password: ""
    })
    .then(function (response) {
         // response  
    }).catch(function (error) {
        // 오류발생시 실행
    })

동시요청

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 두개의 요청이 성공했을 때
  }));

리액트에서 사용하기

axios를 이용해서 GET으로 컴포넌트 처음 렌더링 하면 fetchAPI 함수 호출

setSate를 통해서 state에 API 요청 데이터를 넣어줘서 사용 가능하다

  async function fetchAPI() {
    const response = await fetchAPI();
    const data = response.data;
    setData(data);
  }

  useEffect(() => {
    fetchAPI();
  }, []);

 

onClick하면 axios로 post 요청하기

  const onClick = () => {
    axios
      .post('/api/save', {
        data: data,
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  };

 

전체 코드

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function fetchAPI() {
  return axios.post('/api/keypad');
}

export default function TestComponent() {
  const [data, setData] = useState();

  async function fetchAPI() {
    const response = await fetchAPI();
    const data = response.data;

    setData(data);
  }

  const onClick = () => {
    axios
      .post('/api/password', {
        data: data,
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  useEffect(() => {
    fetchAPI();
  }, []);

  return (
    <>
      <div>{data}</div>
      <button onClick={onClick}></button>
    </>
  );
}

 

 

공식 사이트

https://axios-http.com/kr/docs/intro

리액트 컴포넌트에서 axios API 요청하기