[React] json-server을 이용하여 데이터 받아오기

2022. 7. 15. 09:35·Stack/React

2022.07.14 - [Coding/React] - [React] Redux Middleware - 리덕스 미들웨어

 

[React] Redux Middleware - 리덕스 미들웨어

리덕스 미들웨어 1. 미들웨어 만들기 2. thunk 미들웨어 사용하기 dispatch => 미들웨어 => reducer const middleware = store => next => action => { } function middleware(store) { return function(next){  ..

7ingout.tistory.com

 

npm install axios
npx json-server ./data.json --port 4000

 

api/posts.js

// n 밀리세컨드동안 기다리는 프로미스를 만들어주는 함수

import axios from "axios";

// const sleep = n => new Promise(resolve => setTimeout(resolve, n));
//
// const posts = [
//     {
//         id: 1,
//         title: "리덕스 미들웨어를 공부합시다.",
//         body: "리덕스 미들웨어를 만들어 봅시다."
//     },
//     {
//         id: 2,
//         title: "redux-thunk를 사용해봅시다.",
//         body: "redux-thunk를 사용해서 비동기 작업을 처리해봅시다."
//     },
//     {
//         id: 3,
//         title: "redux-saga도 공부해봅시다.",
//         body: "나중엔 redux-saga를 사용해서 비동기 작업을 처리해보세요."
//     }
// ]

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

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

 

data.json

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

'Stack > React' 카테고리의 다른 글

[React] 회원가입 기능 구현 (MySQL / bcrypt / 쿠키)  (0) 2022.08.03
[React] 고객관리 사이트 (Client) redux로 구현하기  (0) 2022.07.21
[React] Redux Middleware - 리덕스 미들웨어  (0) 2022.07.14
[React] Redux - 리덕스  (0) 2022.07.12
[React] HTML / 자바스크립트로 Redux 맛보기  (0) 2022.07.11
'Stack/React' 카테고리의 다른 글
  • [React] 회원가입 기능 구현 (MySQL / bcrypt / 쿠키)
  • [React] 고객관리 사이트 (Client) redux로 구현하기
  • [React] Redux Middleware - 리덕스 미들웨어
  • [React] Redux - 리덕스
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[React] json-server을 이용하여 데이터 받아오기
상단으로

티스토리툴바