Axios

공룡개발자·2022년 4월 10일
0

fake server인 reqres를 이용해서 Axios 실습해보기!

GET

// pages/Prac.js
import React from "react";
import { useDispatch } from "react-redux";
import { getApi } from "../redux/modules/prac";

const Prac = () => {
    const dispatch = useDispatch();
    
    return(
        <button onClick={() => {
            dispatch(getApi())
        }}>테스트</button>
    )
};

export default Prac;


// redux/modules/prac.js
export const getApi = () => {
    return async function (dispatch, getState, {history}){
        try {
            const response = await axios.get('https://reqres.in/api/users?page=2');
            console.log(response.data);
        } catch(err){
            console.log(err);
        }
    }
}

이렇게 잘 받아왔다. 그 후에는 redux에 데이터를 전달하기 위해 원하는 형식으로 조정해 dispatch하면 될 것 같다.

Post

회원가입한 회원의 이메일과 패스워드를 post해 토큰을 받아오는 과정이다.

// redux/modules/prac.js
export const postApi = () => {
    return async function (dispatch, getState, {history}){
        try {
            const response = await axios.post('https://reqres.in/api/login',{
                email: "eve.holt@reqres.in",
                password: "cityslicka",
            });
            console.log(response);
        } catch(err){
            console.log("에러", err);
        }
    }
}

이번에는 틀린 정보를 전달해보겠다.

없는 회원의 정보라 에러메세지를 전달해준다.

profile
공룡의 발자취

0개의 댓글