React - ajax 1

Inseok Park·2022년 8월 23일
0

React 쇼핑몰 만들기

목록 보기
7/15
post-thumbnail

서버에서 데이터를 요청할 때

정확한 규격에 맞춰서 요청해야하는데

    1. 어떤 데이터인지 (URL 형식으로)
    1. 어떤 방법으로 요청할지 (GET or POST)

AJAX란

서버에 GET, POST 요청을 할 때 새로고침 없이 데이터를 주고받을 수 있게 도와주는
간단한 브라우저 기능을 AJAX라고 한다.

AJAX로 GET/POST요청하려면 방법 3개 중 택1 하면 된다.

    1. XMLHttpRequest라는 옛날 문법 쓰기
    1. fetch()
    1. axios

axios가 가장 편하고 대중적이다.

axios 라이브러리 사용법

설치 & 셋팅

npm install axios 

예시

// axios 라이브러리 불러오기
import axios from 'axios'

function App(){
  const [shoes, setShoes] = useState(shoeData);
  return (
    <button onClick={()=>{
      axios.get('https://codingapple1.github.io/shop/data2.json')
      // 요청 성공 시
      .then((res)=>{
        console.log(res.data)
      })
      // 요청 실패 시
      .catch(()=>{
        console.log('실패함')
      })
    }}>버튼</button>
  )
}

응용 예시
더 보기 버튼 누를 시 위 배열에 데이터를 추가시켜 화면에 출력해보기

(concat 방식)

<button onClick={()=> {
  axios.get('https://codingapple1.github.io/shop/data2.json').then((res)=> {
    let copy = shoes.concat(res.data);
    setShoes(copy);
  })
  .catch(()=>{
    console.log('error')
  })
}}>더 보기</button>

(spread 방식)

<button onClick={()=> {
  axios.get('https://codingapple1.github.io/shop/data2.json').then((res)=> {
  let copy = [...shoes, ...res.data];
      setShoes(copy);
  })
  .catch(()=>{
    console.log('error')
  })
}}>더 보기</button>

출력 성공!

0개의 댓글