일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
- nextJS
- SSH
- CI
- 이미지 포맷 변경
- workflow
- 자동화
- gitgub actions
- 이미지 압축
- 성능 개선
- 배포
- nginx
- 렌더링 과정
- certbot
- webp
- 브라우저
- aws
- pm2
- 검색엔진최적화
- 인증서
- 3-Way HandShake
- tcp
- SSL
- DNS
- 무중단
- ec2
- https
- 로드 밸런싱
- 리버스 프록시
- 이미지 최적화
- TLS
- Today
- Total
개발일기
Next.js로 TodoList 만들기 (with axios, json-server,SWR) 본문
개요
역시 새로운 기술을 사용해서 프로젝트를 만들때는 TodoList만한게 없는거 같다. 그래서 공부중인 Next.Js를 사용하면서 처음 사용해보는 SWR도 같이 써보려고 한다.
프로젝트를 생성하고 기본적인 것들을 이것저것 만들어 봤을 때에는 react와는 그렇게 다르지 않았다.
하지만 폴더구조를 잡는게 쉽지 않았고 nextJs에 대한 정보가 그렇게 많지 않았던 것 같다. 나의 이해력의 문제일 수도 있다. 아무튼 구현했던 것들을 기록하려고 한다.
폴더구조
먼저 pages 폴더 안에 custom App을 생성해 주었다.
Custom _app의 장점은 전역적인 레이아웃, 상태 관리, 데이터 가져오기, 라우팅 설정, 스타일링 및 테마 관리 등을 단일한 곳에서 처리할 수 있다. 또한 _app은 페이지가 렌더링되기 전에 실행되므로 애플리케이션의 초기 설정을 처리하는 데에도 적합하다.
따라서 _app을 사용하여 애플리케이션의 전역적인 설정 및 기능을 관리할 수 있으며, 필요에 따라 pages 디렉토리의 파일과 layout 컴포넌트도 함께 사용하여 페이지별로 특화된 로직을 처리할 수 있다.
컴포넌트
Page.jsx
import Image from "next/image";
import Form from "./components/todoList/Form";
import Header from "./components/todoList/Header";
import TodoList from "./components/todoList/TodoList";
export default function Home() {
return (
<>
<Header />
<Form />
<TodoList/>
</>
);
}
Header.jsx
import React from "react";
const Header = () => {
return (
<header className="flex justify-center p-10">
<h1 className="text-3xl font-bold">TodoList NextJS</h1>
</header>
);
};
export default Header;
Form.jsx
"use client";
import React,{ useState } from "react";
import axios from "axios";
import uuid from "react-uuid";
import { Button } from "@mui/material";
import useSWR from "swr";
import { fetcher } from "@/app/swr";
const Form = () => {
const [inputText, setInputtext] = useState("");
const { mutate, error } = useSWR(
process.env.NEXT_PUBLIC_URL,
fetcher
);
const addTodoHandler = async(e) => {
e.preventDefault()
const newTodo = {
id: uuid(),
todo: inputText,
};
await axios.post(process.env.NEXT_PUBLIC_URL, newTodo);
mutate()
};
return (
<form className="flex justify-center items-center gap-2 mb-8">
<label>TODO : </label>
<input
className="border w-4/12"
type="text"
placeholder="Enter Todo"
value={inputText}
onChange={(e) => setInputtext(e.target.value)}
></input>
<Button variant="contained" size="small" onClick={addTodoHandler}>ADD</Button>
<Button variant="outlined" size="small" type="button" onClick={() => setInputtext("")}>CLEAR</Button>
</form>
);
};
export default Form;
TodoList.jsx
"use client";
import React from "react";
import { fetcher } from "@/app/swr";
import { Button } from "@mui/material";
import axios from "axios";
import useSWR from "swr";
const TodoList = () => {
const { data: todoList,mutate, error } = useSWR(
process.env.NEXT_PUBLIC_URL,
fetcher
);
const todoDelHandler = async(id) => {
await axios.delete(`${process.env.NEXT_PUBLIC_URL}/${id}`);
mutate()
};
return (
<main className="">
{todoList?.map((todo) => {
return (
<div
key={todo.id}
className="flex justify-between bg-red-200 p-2 rounded-md mb-2"
>
<div className="flex gap-2">
<input type="checkbox"></input>
<h1 className="text-lg">{todo.todo}</h1>
</div>
<div className="flex gap-2">
<Button variant="contained" size="small">
Edit
</Button>
<Button
variant="contained"
size="small"
onClick={() => todoDelHandler(todo.id)}
>
Delete
</Button>
</div>
</div>
);
})}
</main>
);
};
export default TodoList;
SWR 사용해보기
나는 프로젝트를 진행할 때마다 데이터를 편하게 관리해주는 라이브러리로 보통 ReactQuery를 사용했지만 뭔가 새로운 걸 사용해보고 싶었다. 그래서 다른게 뭐가 있을까 찾아 봤는데 Apollo GraphQL 이라는게 있었다. 어? 이거 좀 재밌겠는데? 생각하고 열심히 찾고, 프론트단에서 코드도 잘 구현 했는데 실행되지 않았다. 뭐가 문제일까 또 찾아본 결과,,, 백엔드쪽도 따로 구현을 해줘야 했다,,,,,,,,,,,,,,다음에 알아보기로 했다. 그래서 나온 차선책 SWR ! 사용해보면서 너무 편하고, 옵션 설정 및 mutate기능 또한 간단하게 구현 할 수 있었다.
SWR/index.js
import axios from "axios";
export const fetcher = async (url) => {
const response = await axios.get(url);
return response.data
};
공식문서에 나와있듯 먼저 fetcher라는 함수를 생성한다. 정답이 없이 개발환경에 맞게 데이터를 받아오면 된다.
이후 사용할 페이지에서 useSWR을 사용하여 데이터를 사용하면 된다.
const{data, error, isLoading, isValidating, mutate} = useSWR(key, fetcher, options)
공식문서에 나온 내용이다. 간단하게 key에 통신할 주소를 입력하면 만들어둔 fetcher 함수의 파라미터 값으로 key값이 들어가고 호출하게 된다. 그렇게 호출된 데이터를 사용하면 되고 error, isLoading 등 다양한 옵션은 프로젝트에 맞게 사용하면 된다.
레이아웃 및 디자인
일단 흔히 볼 수 있는 TodoList 레이아웃이다. 현재는 작성, 삭제까지 구현한 상태이고 수정 부분은 라우팅 공부 후에 업로드 할 예정이다.