본문 바로가기

React

[axios&api] http://localhost:3000/ & http://localhost:4000/

깃헙 주소 : https://github.com/webcreastory/react-axios-lesson3.git

 

// src > axios폴더 > api.js

import axios from "axios";

const instance = axios.create({
    baseURL: process.env.REACT_APP_SERVER_URL,
    // timeout: 1, // 0.001초 // 1000, // 1초
});

instance.interceptors.request.use(

    // 요청을 보내기 전 수행되는 함수
    function(config){
        console.log('인터셉터 요청 성공!');
        return config;
    },
    
    // 오류 요청을 보내기 전 수행되는 함수
    function(error){
        console.log('인터셉터 요청 오류!');
        return Promise.reject(error);
        
    },
    )
    instance.interceptors.response.use(
        
    // 응답을 내보내기 전 수행되는 함수
    function(response){
        console.log("인터셉터 응답 받았습니다!");
        return response;
    },

    // 오류 응답을 내보내기 전 수행되는 함수
    function(error){
        console.log("인터셉터 응답 오류 발생")
        return Promise.reject(error);
    },
)

export default instance;
// root > db.json

{
  "todos": [
    {
      "id": 1,
      "title": "하나"
    },
    {
      "id": 2,
      "title": "둘"
    },
    {
      "id": 3,
      "title": "three"
    },
    {
      "id": 4,
      "title": "four"
    },
    {
      "title": "다섯",
      "id": 5
    },
    {
      "title": "여섯",
      "id": 6
    },
    {
      "title": "eight",
      "id": 8
    }
  ]
}
//App.jsx

import { useEffect, useState } from 'react';
import './App.css';
// import axios from 'axios';
import api from './axios/api';

function App() {
    const [todos, setTodos] = useState(null);
    const [inputValue, setInputValue] = useState({
        title: '',
    });
    const [targetId, setTargetId] = useState('');
    const [contents, setContents] = useState('');

    // 조회 함수 // 비동기 함수 : 서버(json-server)에 todos를 요청하는 함수
    const fetchTodos = async () => {
        // const { data } = await axios.get('http://localhost:4000/todos');
        // const { data } = await axios.get(`${process.env.REACT_APP_SERVER_URL}/todos`);
        const { data } = await api.get("/todos");
        // console.log('data', data);
        setTodos(data);
    };

    // 추가 함수
    const onSubmitHandler = async () => {
      api.post("/todos", inputValue);
        // setTodos([...todos, inputValue]);
        fetchTodos();
    };

    // 삭제 함수
    const onDeleteBtnClickHandler = async (id) => {
      api.delete(`/todos/${id}`);
        setTodos(
            todos.filter((item) => {
                return item.id !== id;
            })
        );
    };

    // 수정 함수
    const onUpdateBtnClickHandler = async () => {
      api.patch(`/todos/${targetId}`, {
            title: contents,
        });

        setTodos(
            todos.map((item) => {
                if (item.id == targetId) {
                    return { ...item, title: contents };
                } else {
                    return item;
                }
            })
        );
    };

    useEffect(() => {
        // db로 부터 값을 가져올 것이다.
        fetchTodos();
    }, []);

    return (
        <>
            <div>
                {/* 수정 영역 */}
                <input
                    type="text"
                    placeholder="수정할 아이디"
                    value={targetId}
                    onChange={(e) => {
                        setTargetId(e.target.value);
                    }}
                />
                <input
                    type="text"
                    placeholder="수정할 내용"
                    value={contents}
                    onChange={(e) => {
                        setContents(e.target.value);
                    }}
                />
                <button onClick={onUpdateBtnClickHandler}>수정</button>
                <br />
                <br />
            </div>
            <div>
                {/* input영역 */}
                <form
                    onSubmit={(e) => {
                        e.preventDefault();

                        // 버튼 클릭시, input에 들어있는 값(state)을 이용하여 DB에 저장(post요청)
                        onSubmitHandler();
                    }}
                >
                    <input
                        type="text"
                        value={inputValue.title}
                        onChange={(e) => {
                            setInputValue({
                                title: e.target.value,
                            });
                        }}
                    />
                    <button type="submit">추가</button>
                </form>
            </div>

            <div>
                {/* 데이터 영역 */}
                {todos?.map((item) => {
                    return (
                        <div key={item.id}>
                            {item.id} : {item.title}
                            &nbsp;<button onClick={() => onDeleteBtnClickHandler(item.id)}>삭제</button>
                        </div>
                    );
                })}
            </div>
        </>
    );
}

export default App;
// root > .env

REACT_APP_SERVER_URL=http://localhost:4000
// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  // <React.StrictMode>  // 콘솔창에 중복 없앰
    <App />
  // </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

'React' 카테고리의 다른 글

컴포넌트 스타일링  (0) 2024.01.06
Thunk 기본 세팅_setTimeout 3초(+ / -)  (0) 2024.01.06
이벤트 핸들링(Event Handling)  (1) 2024.01.05
ref : DOM에 이름 달기  (0) 2024.01.05
컴포넌트 분리's 정석  (0) 2024.01.05