react 비동기통신을 위한 라이브러리 axios
먼저 Json-server 를 설치함.
그 이전에 선행되어야 할 항목
vite으로 진행 시
→ yarn create vite@latest
→ 경로이동
→ yarn install
→ yarn add axios
CRA로 진행 시
yarn add axios
json서버와 개발자 브라우저를 동시에 실행하기 위해서는 터미널을 2개 사용
yarn json-server --watch 데이터베이스이름.json --port 원하는포트
ex) yarn json-server --watch db.json --port 4000
다른 터미널에서는...
yarn run dev
CRUD
CRUD는 각각 post, get, patch, delete를 사용하였다.
db.JSON
{
"todos": [
{
"id": "1",
"title": "react"
},
{
"id": "2",
"title": "node"
},
{
"id": "3",
"title": "spring"
}
]
}
Get
데이터를 불러오기 위해서는 const {data} = axios.get('<http://localhost:4000>') 이용했다.
데이터를 그려줄 useState를 생성한다.
const [todos, setTodos] = useState(null);
이 테이터가 만약 페이지 랜더링 초기부터 존재해야 한다면,
useEffect를 통해서 불러준다 useEffect (()=>{axios를 포함한 데이터를 불러오는 함수},[])
* 의존성 배열에 빈 배열을 넣으면 마운트 되는 최초 1회에만 실행이 된다
Post
데이터를 생성,추가하기 위해서는 axios.post('<http://localhost:4000>', 추가할 값)
여기서 추가할 값을 브라우저에서 리랜더링하고 싶기 때문에 useState를 통해 변경된 내용이 추가하기.
여기서는 변경하고 싶은 값을 title하나만 두었기 때문에, db에 있는 title에만 변경값을 주었다.
const [inputValue, setInputValue] = useState({
title: '',
});
...
return (
...
<input
type="text"
value={inputValue.title}
onChange={(e) => {
setInputValue({ title: e.target.value })
}}
/>
<button type="submit">추가</button>
Update
업데이트를 위한 폼을 만든다.
화면에 그리기 위해서 useState를 이용해준다.
const [targetId, setTargetId] = useState('');
const [contents, setContents] = useState('');
...
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>
</div>
데이터를 업데이트 하기 위해서는 axios.patch(`http://localhost:4000/totods/${targetId}`,{
title: contents
})
contents를 새로 그려주기 위해서 setState를 이용한다.
함수형 업데이트
setTodos(todos.map(item =>{
if(item.id == targetId {
retrun {...item, title: contents}
} else {
return item,
}
})
);
Delete
DB데이터의 데이터를 삭제하기 위해선 axios.delete(`http://localhost:4000/todos/${id}`)
를 이용했다.
마찬가지로 상태가 적용되어야 하기때문에 setState를 이용했다.
함수형 업데이트
setTodos(todos.filter(item =>{
retrun item.id !==id;
}))
사용한 전체 코드
누르면 코드가 펼쳐집니다.
더보기
import axios from "axios"
import { useEffect, useState } from "react"
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 onSubmitHandler = async () => {
await axios.post('http://localhost:4000/todos', inputValue)
// setTodos([...todos, inputValue])
fetchTodos();
}
const onDeleteBtnClickHandler = async (id) => {
axios.delete(`http://localhost:4000/todos/${id}`)
setTodos(todos.filter(item => {
return item.id !== id;
}))
}
const onUpdateBtnClickHandler = 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()
}, [])
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>
<form onSubmit={(e) => {
e.preventDefault();
onSubmitHandler();
}}>
<input
type="text"
value={inputValue.title}
onChange={(e) => {
setInputValue({ title: e.target.value })
}}
/>
<button type="submit">추가</button>
</form>
</div>
<section>
{todos?.map((item) => {
return (
<div key={item.id}>
<ul>
<li>{item.id}</li>
<li>{item.title}</li>
<button onClick={() => onDeleteBtnClickHandler(item.id)}>삭제</button>
</ul>
</div>
)
})}
</section>
</>
)
}
export default App
'React' 카테고리의 다른 글
2024.2.21 기록 (redux-thunk에 대한 짧은 이야기) (0) | 2024.02.21 |
---|---|
2024.2.20 기록 (프로젝트를 하며 나온 자잘한 실수) (0) | 2024.02.20 |
2024.2.16 기록 ( vite, 자바스크립트의 배열과 객체) (0) | 2024.02.16 |
2024.2.15 기록 (프로젝트 마무리 회고) (0) | 2024.02.15 |
2024. 2.14 기록 (styled-components) (0) | 2024.02.14 |