생활코딩

Coding Everybody

코스 전체목록

닫기

수정 기능 구현

수정 기능은 read + create 기능을 합친 것과 같습니다. 

소스코드

https://github.com/egoing/nextapp/commit/3938ee91148d7bd8096211866e4cc26e3f64662b

절차

1. app/update/[id]/page.js 생성

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
31
32
33
34
35
36
37
38
39
'use client'
import { useRouter } from "next/navigation";
import {useEffect, useState} from 'react';
export default function Update(props){
const router = useRouter();
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const id = props.params.id;
async function refresh(){
const resp = await fetch(`http://localhost:9999/topics/${id}`);
const topic = await resp.json();
setTitle(topic.title);
setBody(topic.body);
}
useEffect(()=>{
refresh();
}, []);
return <form onSubmit={async evt=>{
evt.preventDefault();
const title = evt.target.title.value;
const body = evt.target.body.value;
const resp = await fetch(`http://localhost:9999/topics/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({title, body})
});
const topic = await resp.json();
router.push(`/read/${topic.id}`);
router.refresh();
}}>
<h2>Update</h2>
<p><input type="text" name="title" placeholder="title" onChange={e=>setTitle(e.target.value)} value={title}/></p>
<p><textarea name="body" palceholder="body" onChange={e=>setBody(e.target.value)} value={body}></textarea></p>
<p><input type="submit" value="update" /></p>
</form>
}

2. read 페이지 캐슁 끄기

수정을 한 후에 /read/[id]로 접속을 하면 내용이 갱신되지 않습니다. 여기서는 캐쉬 기능을 끄겠습니다. 

1
2
3
4
5
6
7
8
9
export default async function Read(props){
const id = props.params.id;
const resp = await fetch(`http://localhost:9999/topics/${id}`, {cache:'no-cache'});
const topic = await resp.json();
return <>
<h2>{topic.title}</h2>
{topic.body}
</>
}

댓글

댓글 본문
  1. 수정 기능 구현. cache 개념도 더 익혀야 하고 할 것이 많음.
버전 관리
egoing
현재 버전
선택 버전
공동공부
graphittie 자세히 보기