며칠째 node js + react + sql 연결에 곤란을 겪고 있던 차에 ㅜㅜ (CRUD라도 해보고 싶은데) 친구가 json-server라도 써보라며 던져주고 갔다.
물론 나는 처음 들어보는 문물이었기 때문에 기록용 게시물을 하나 남김!
special thanks to 친절하게 예시까지 작성해준 내친구 jaenny❤👍
json server는 아주 짧은 시간에 REST API 를 구축해주는 라이브러리이다. 약간 데모버전의 서버를 구축해준다고 생각하면 될듯! REST API 서버의 기본적인 기능을 대부분 갖추고 있으나 배포용으로는 적절하지 않고 프로토타입이나 토이프로젝트에 사용하기 좋다.
npx create-react-app (폴더명)
npm install -g json-server
json-server --watch db.json
이때 데이터베이스의 역할을 하는 db.json 파일이 생성된다.
나는 이렇게 설정해둠!
{
"posts": [
{
"id": 1,
"title": "제목2",
"author": "작가1수정"
},
{
"id": 2,
"title": "제목2",
"author": "작가2"
},
{
"id": 3,
"title": "dd",
"author": "fffgg"
}
],
"comments": [],
"profile": {
"name": "typicode"
}
}
json-server --watch db.json --port 4000
npm install axios
import React from 'react';
import axios from 'axios';
const Sample = () => {
const [posts, setPosts] = React.useState([]);
const [form, setForm] = React.useState({ id: '', title: '', author: '' });
const [update, setUpdate] = React.useState({ id: '', title: '', author: '' });
const { id, title, author } = update;
const [open, setOpen] = React.useState(false);
React.useEffect(() => {
// read
axios({ url: 'http://localhost:4000/posts', method: 'GET' }).then(
({ data }) => setPosts(data)
);
}, []);
return (
<div style={{ padding: 20 }}>
<div
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
border: '1px solid black',
}}
>
<div style={{ marginRight: 10 }}>title: </div>
<input
type='text'
style={{ color: 'black', width: 80 }}
value={title}
onChange={(e) => {
setForm((prev) => ({ ...prev, title: e.target.value }));
setUpdate((prev) => ({ ...prev, title: e.target.value }));
}}
/>
<div style={{ marginRight: 10 }}>author: </div>
<input
type='text'
style={{ color: 'black', width: 80 }}
value={author}
onChange={(e) => {
setForm((prev) => ({ ...prev, author: e.target.value }));
setUpdate((prev) => ({ ...prev, author: e.target.value }));
}}
/>
<button
onClick={() => {
// create
if (open === false) {
axios({
url: 'http://localhost:4000/posts',
method: 'POST',
data: form,
}).then(({ data }) => setPosts((prev) => [...prev, data]));
}
// update
else {
axios({
url: `http://localhost:4000/posts/${id}`,
method: 'PUT',
data: form,
}).then(({ data }) =>
setPosts((prev) =>
prev.map((post) => (post.id === id ? data : post))
)
);
setUpdate((prev) => ({
...prev,
id: '',
author: '',
title: '',
}));
setOpen(false);
}
}}
>
{open ? '수정완료' : '제출'}
</button>
</div>
{posts.map((post) => {
return (
<div
key={`post_${post.id}`}
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
}}
>
<div style={{ marginRight: 10, border: '1px solid black' }}>
ID: {post.id}
</div>
<div style={{ marginRight: 10, border: '1px solid black' }}>
title: {post.title}
</div>
<div style={{ marginRight: 10, border: '1px solid black' }}>
author: {post.author}
</div>
<button
onClick={() => {
setUpdate((prev) => ({
...prev,
id: post.id,
author: post.author,
title: post.title,
}));
setOpen(true);
}}
>
수정
</button>
<button
onClick={() => {
// delete
axios
.delete(`http://localhost:4000/posts/${post.id}`)
.then(() =>
setPosts((prev) =>
prev.filter((item) => post.id !== item.id)
)
)
.catch((e) => {
console.log(e);
});
}}
>
삭제
</button>
</div>
);
})}
</div>
);
};
export default Sample;