노력이 좋아서

<step81>'redux(react)_리덕스 미들웨어_2'

zoaseo 2022. 7. 15. 09:13

1) 

json에서 데이터 받아오기

data.json

{
    "posts": [
        {
            "id": 1,
            "title": "리덕스 미들웨어를 공부합시다",
            "body": "리덕스 미들웨어를 만들어 봅시다"
        },
        {
            "id": 2,
            "title": "redux-thunk를 사용해봅시다",
            "body": "redux-thunk를 사용해서 비동기 작업을 처리해봅시다"
        },
        {
            "id": 3,
            "title": "redux-saga도 공부해봅시다",
            "body": "redux-saga를 사용해서 비동기 작업을 처리해보세요"
        }
    ]
}
npx json-server ./data.json --port 4000

npm install axios

 

api/posts

import axios from "axios";

// 포스트 목록을 가져오는 비동기 함수
export const getPosts = async () => {
    const response = await axios.get("http://localhost:4000/posts");
    return response.data;
}

// ID로 포스트를 조회하는 비동기 함수
export const getPostById = async id => {
    const response = await axios.get("http://localhost:4000/posts");
    return response.data.find(post => post.id === id); // id로 찾아서 반환
}