I’m making React/Next app with CRUD.
About update form, I made some code below.
This code is fetching existing data and after renewing the data, updating through api.
Regrettably this code has big problem.
If you don’t update input form, the data that is title and content will disappear without trace.
I understand updating data could be done only when setTitle and setContent work.
But I don’t know how to fix this code as I expected.
If you only updated the title, the content would be clear after pushing submit button.
Like this.
Before
- title: aaa
- content: bbb
Update title aaa to aaaa
After
- title: aaaa
- content:
My code is here.
import Link from "next/link";
import { client } from "@/libs/client";
import { useRouter } from "next/router";
import React, { useState } from "react";
export default function Update ({ blog }) {
const router = useRouter()
const id = blog.id;
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
async function update(event) {
event.preventDefault()
client.update({
endpoint: "blogs",
content: {
title: title,
content: content,
},
contentId: id
}).then((res) => {
if (res.status === 401) {
alert("Something wrong is happening")
} else {
alert("Editing is done")
router.push(`/`)
}
})
}
return (
<>
<div className='main'>
<h1 className=''>Edit page</h1>
<div className="contents">
<div>
<form onSubmit={ update }>
<div>
<h2>Here's title</h2>
<input name="title" type="text" defaultValue={blog.title} onChange={(event) => setTitle(event.target.value)} />
</div>
<div>
<h2>Contents</h2>
<textarea name="content" defaultValue={blog.content} onChange={(event) => setContent(event.target.value)} ></textarea>
</div>
<button type="submit">
<p>Submit</p>
</button>
</form>
</div>
</div>
</div>
</>
);
}
export const getStaticPaths = async () => {
const data = await client.get({ endpoint: "blogs" });
const paths = data.contents.map((content) => `/blog/${content.id}/update`);
return { paths, fallback: false };
};
export const getStaticProps = async (context) => {
const id = context.params.id;
const data = await client.get({ endpoint: "blogs", contentId: id });
return {
props: {
blog: data,
},
};
};