Axios

HYOJIN·2021년 10월 15일
0

React

목록 보기
9/9
post-thumbnail

실행 방법

  1. 패키지 설치
yarn install
  1. json-server 실행
npx json-server ./data.json --port 4000
  1. 프로젝트 실행
    (json-server와 터미널을 따로 두고 실행해야함)
yarn start

Axios

axios.js

  • axios를 사용하여 인스턴스 생성후 모듈화하여 사용
import axios from 'axios';

const instance = axios.create({
    // 기본 서버 주소
    baseURL : 'http://localhost:4000/',
    headers: {
    	'content-type': 'applicatoin/json;charset-UtF-8',
        accept: 'application/json',
    },
});
  • baseURL을 미리 지정했기 때문에 함수의 첫번째 인자에 들어가는 url은
    -> http://localhost:4000/ + 내가 작성한 url ('/posts')
    이곳으로 요청을 보냄

  • get과 delete는 두 번째 인자에 데이터를 담아 보낼 수 없기 때문에 서버에 데이터를 보낼 경우 쿼리를 이용해서 보냄

export const apis = {
     // 게시물 불러오기
     getPost: () => instance.get('/posts'),
     // 게시물 작성하기
     createPost: (contents) => instance.post('/posts', contents),
     // 게시물 수정하기
     editPost: (id, content) => instance.put(`/posts/${id}`, contents),
     // 게시물 삭제하기
     delPost: (id) => instance.delete(`/posts/${id}`),
);

Json-server

  • Node를 기반으로 구동되는 API-Server로 별도의 서버가 없는 환경에서 프론트엔드 작업을 진행할 때 사용
import React, { useEffect, useState } from 'react';
import './App.css';
import { apis } from './axois';

function App(){
    const [list, seList] = useState([]);

    useEffect(() => {
    
        // apis.getPost()로 서버에 요청 보내기
        // .then과 .catch로 성공, 실패 로직 구현
        apis
            .getPost()
            .then((res) => {
                const post = res.data;
                setList(...list, post);
            })
            .catch((err) => {
                console.error(err);
            });
    },[]);
    return(
        <div className='App'>
            {list &&
                list.map((item) => {
                    return(
                        <div key={item.id}>
                            <h2>{item.title}</h2>
                            <p<{item.body}</p>
                        </div>
                    );
                })};
        </div>
    )
}

export default App;

Redux-thunk

post.js

import {createAction, handleActions} from 'redux-actions';
import {produce} from 'immer';
import {apis] from '../lib/axios';

action

const LOAD_POST = 'LOAD_POST';

action creators

const loadPost = createAction(LOAD_POST, (list) => ({list}));

middleware

const getPostMiddleware = () => {
    return (dispatch) => {
        // axios 모듈을 통해 getPost() 실행
        apis
            .getPost()
            .then((res) => {
                const post_list = res.data;
                // 받아온 데이터 redux에 담기
                dispatch(loadPost(post_list));
            })
            .catch((err) => {
                console.error(err);
            })
    }
}

reducer

export default handleActions(
    {
        [LOAD_POST]: (state, action) => 
            produce(state, (draft) =>{
                draft.list = action.payload.list;
            }),
    },
    initialState
)

export

const postCreators = {
    getPostMiddleware
};

export {postCreators};

middleware 활용

import React, {useEffect} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import './App.css';
import {postCreators} from './redux/post';

function App(){
    const dispatch = useDispatch();
    const post = useSelector((state) => state.post.list);
    
    // middleware 함수 dispatch
    useEffect(()=>{
    	dispatch(postCreators.getPostMiddleware());
    }, []);
    
    // useSelector로 사용하고자하는 list 가져오기
    return (
        <div className='App'>
            {post &&
                post.map((item) => {
                    return (
                        <div key={item.id}>
                            <h2>{item.title}></h2>
                            <p>{item.body}</p>
                        </div>
                        );
                    })
            }
        <div>
    )
}

export default App;
profile
https://github.com/hyojin-k

0개의 댓글