yarn add axios
yarn add json-server
import "./App.css";
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [todos, setTodos] = useState(null);
const [inputValue, setInputValue] = useState({ title: "" });
const [targetId, setTargetId] = useState("");
const [contents, setContents] = useState("");
//조회 함수
const fetchTodos = async () => {
const { data } = await axios.get("http://localhost:4000/todos");
// console.log("data", data);
setTodos(data);
};
// 추가 함수
const onSubmitHanlder = async () => {
axios.post("http://localhost:4000/todos", inputValue);
setTodos([...todos, inputValue]);
fetchTodos();
};
//삭제 함수
const onDeleteButtonHandler = async (id) => {
axios.delete(`http://localhost:4000/todos/${id}`);
setTodos(
todos.filter((item) => {
return item.id !== id;
})
);
};
// 수정 함수
const onUpdateButtonHandler = async () => {
axios.patch(`http://localhost:4000/todos/${targetId}`, {
title: contents,
});
setTodos(
todos.map((item) => {
if (item.id == targetId) {
return { ...item, title: contents };
} else {
return item;
}
})
);
};
useEffect(() => {
fetchTodos();
//db로부터 값을 가져올 것이다.
}, []);
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={onUpdateButtonHandler}>수정</button>
<br />
<br />
</div>
<div>
{/* input 영역 */}
<form
onSubmit={(e) => {
e.preventDefault();
//디폴트 기능을 막아서 form 고유특성인 새로고침을 막는다
// 버튼 클릭시 input에 들어있는 값(state)를 이용하여 DB에 저장(POST 요청)
onSubmitHanlder();
}}
>
<input
type="text"
value={inputValue.title}
onChange={(e) => {
setInputValue({
title: e.target.value,
});
}}
/>
<button>추가</button>
</form>
</div>
<div>
{/* 데이터 영역 */}
{todos?.map((item) => {
//옵셔널 체이닝
return (
<div key={item.id}>
{item.id} : {item.title}
<button onClick={() => onDeleteButtonHandler(item.id)}>
삭제
</button>
</div>
);
})}
</div>
</>
);
}
export default App;
CASE 1. 데이터 읽어오기
fetch
const url = "https://jsonplaceholder.typicode.com/todos";
fetch(url)
.then((response) => response.json())
.then(console.log);
axios
const url = "https://jsonplaceholder.typicode.com/todos";
axios.get(url).then((response) => console.log(response.data));
CASE 2. 에러 처리
axios
const url = "https://jsonplaceholder.typicode.com/todos";
axios
.get(url)
.then((response) => console.log(response.data))
.catch((err) => {
console.log(err.message);
});
error handling
이 가능하다.const url = "https://jsonplaceholder.typicode.com/todos";
// axios 요청 로직
axios
.get(url)
.then((response) => console.log(response.data))
.catch((err) => {
// 오류 객체 내의 response가 존재한다 = 서버가 오류 응답을 주었다
if (err.response) {
const { status, config } = err.response;
// 없는 페이지
if (status === 404) {
console.log(`${config.url} not found`);
}
// 서버 오류
if (status === 500) {
console.log("Server error");
}
// 요청이 이루어졌으나 서버에서 응답이 없었을 경우
} else if (err.request) {
console.log("Error", err.message);
// 그 외 다른 에러
} else {
console.log("Error", err.message);
}
});
fetch
const url = "https://jsonplaceholder.typicode.com/todos";
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(
`This is an HTTP error: The status is ${response.status}`
);
}
return response.json();
})
.then(console.log)
.catch((err) => {
console.log(err.message);
});
fetch의 경우, catch()가 발생하는 경우는 오직 네트워크 장애 케이스이다. 따라서 개발자가 일일히 then() 안에 모든 케이스에 대한 HTTP 에러 처리를 해야한다.