axios 란 node.js와 브라우저를 위한 Promise 기반 http 클라이언트
즉, http를 이용해서 서버와 통신하기 위해 사용하는 패키지이다.
Axios 설치하기
yarn add axios npm install axios
axios / jsonserver 실행하여 확인하기
axios.get(url[, config]) // GET
url에는 서버의 url이 들어가고, config에는 기타 여러가지 설정을 추가할 수 있다.
config는 axios 공식문서에서 확인할 수 있다.
https://axios-http.com/kr/docs/req_config
db.json
app.jsx
오류 파튀~~
await에서 실행 되기 전에 map함수가 돌아가게됨 => 인자가 없어서 화면에 랜더링이 안됨
옵셔널 체이닝
옵셔널 체이닝(optional chaining) ?.을 사용하면 프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 접근할 수 있습니다.
수정하니
정상 적으로 출력됨
axios.post(url[, data[, config]]) // POST
위에서 만든 코드에 input과 button을 추가 해주고 form태그로 감싸준다.
onSubmitHandler 함수를 만들어준다.
axios.post("http://localhost:4000/todos", inputValue);
//axios 에 post요청, todos에 새로 생성되는 inputValue를 넣어줌
setTodos([...todos, inputValue]);
// setTodos에 값을 넣어 다시 랜더링 시켜줌 (새로고침없이도 반영이됨)
제이슨 서버에서는 자동으로 id값이 부여되어서 추가 해주지 않아도 된다 .
1) 삭제 버튼 만들기
2) 삭제 버튼 onclick함수 만들기
인자에 id를 넣어주고 todos/${id} 로 클릭한 놈을 지울 수 있도록 해줌
또한 setTodos에 filter를 걸어서 클릭한 놈이 아닌 애들만 랜더링 되도록 해준다
( 새로고침을 하지 않아도 자동으로 바뀌도록 )
1) input 만들기 ( 수정할 놈 id입력창, 수정할 내용 입력창)
2)useState
3)useState와 연결해주기
4) 수정함수
axios.patch(http://localhost:4000/todos/${targetId}
// targetId는 useState에서 지정한 값임
item.id == targetId // 형식이 다르기 때문에 ==연산자를 씀
//추가함수 const onSubmitHandler = async () => { axios.post("http://localhost:4000/todos", inputValue); fetchTodos(); };
추가하는 함수 작성시
setTodos([...todos, inputValue]);
를 할 경우에는 id값이 제이슨 서버에는 자동으로추가 되지만 화면에는 추가가 안된다. 따라서 이경우 다시 데이터를 불러오는 fetch함수를 써주는 것이 더 좋다 .
최종 코드
import { useEffect, useState } from "react";
import "./App.css";
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 () => {
//axios 관련 내용 넣기
const { data } = await axios.get("http://localhost:4000/todos");
console.log("data", data);
setTodos(data);
};
//추가함수 : submit클릭시 post 요청을 해야함 =async사용
const onSubmitHandler = async () => {
axios.post("http://localhost:4000/todos", inputValue);
//setTodos([...todos, inputValue]);
fetchTodos();
};
//삭제함수
const onDeleteBtnHandler = async (id) => {
axios.delete(`http://localhost:4000/todos/${id}`);
setTodos(
todos.filter((item) => {
return item.id !== id;
})
);
};
//수정함수
const onUpdateHandler = 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(() => {
//db로 부터 값 가저오기
fetchTodos();
}, []);
return (
<>
<div>
{/* 수정영역 */}
<input
type="text"
placeholder="수정할 아이디"
value={targetId}
onChange={(e) => {
setTargetId(e.target.value);
}}
></input>
<input
type="text"
placeholder="수정할 내용"
value={contents}
onChange={(e) => {
setContents(e.target.value);
}}
></input>
<button onClick={onUpdateHandler}>수정</button>
</div>
<br></br> <br></br>
<div>
{/* input영역 */}
<form
// submit의속성-버튼클릭시 새로고침되는것을 막아줌
onSubmit={(e) => {
e.preventDefault();
// 버튼 클릭시 , input에 있는 값을 이용하여 Db에 저장=post요청하기
onSubmitHandler();
}}
>
<input
type="text"
value={inputValue.title}
onChange={(e) => {
setInputValue({ title: e.target.value });
}}
></input>
<button>추가 </button>
</form>
</div>
<div>
{/* 출력 */}
{todos?.map((item) => {
return (
<div>
{item.id} : {item.title}
<button onClick={() => onDeleteBtnHandler(item.id)}>삭제 </button>
</div>
);
})}
</div>
</>
);
}
export default App;