0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Reactで編集機能を作る

Last updated at Posted at 2022-02-06

自己紹介

現在都内の企業でWebエンジニアのインターン生としてお世話になっている大学2年生です!
インターンや個人開発で学んだことや苦労したことを記事にしています!
よろしくお願いします🙇🏻‍♂️

実現したいこと

よくある編集機能を実現したい
1.編集ボタンを押す
2.モーダルが開き、そこにあるフォームに現在の値が入る
3.そのモーダルは値を変えることができ、完了ボタンを押すとその値を保存できる

結論

import React, { memo, useCallback, useEffect, useState } from "react";
import Modal from "react-modal";

export const SUDPost = memo(() => {
  const [posts, setPosts] = useState([]);
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [edit, setEdit] = useState({ post: "" });

  //削除
  const onClickDelete = (id) => {
    window.confirm("本当に削除しますか?") &&
      fetch("http://localhost:8080/timeline/post/delete/" + id, {
        method: "DELETE",
      }).then(() => {
        window.location.reload();
      });
  };

  //複製
  const onClickDuplicate = (id) => {
    fetch("http://localhost:8080/timeline/post/get/" + id)
      .then((res) => res.json())
      .then((json) => {
        const data = {
          post: json.post,
        };
        fetch("http://localhost:8080/timeline/post/post", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        }).then(() => {
          alert("複製完了しました。");
          window.location.reload();
        });
      });
  };

  //編集
  //投稿一覧を取ってくる
  useEffect(() => {
    fetch("http://localhost:8080/timeline/post/get")
      .then((res) => res.json())
      .then((json) => {
        setPosts(json);
      });
  }, []);

  const onClickEdit = useCallback((id) => {
    //モーダルを開く
    setModalIsOpen(true);
    fetch("http://localhost:8080/timeline/post/get/" + id)
      .then((res) => res.json())
      .then((json) => {
        //取ってきた投稿を保持
        console.log(json);
        setEdit(json);
      });
  }, []);

  //フォームの中を変更できるようにする
  const handleEdit = useCallback((e) => {
    const { name, value } = e.target;
    setEdit({ [name]: value });
  }, []);

  //更新
  const onClickUpdate = useCallback(
    (postId) => {
      const data = {
        post: edit.post,
      };
      //保持したidを使って更新
      fetch("http://localhost:8080/timeline/post/put/" + postId, {
        method: "PUT",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      }).then(() => {
        alert("編集完了しました。");
        window.location.reload();
      });
    },
    [edit]
  );

  return (
    <>
      {posts.map((post) => (
        <ul key={post.id}>
          <li>
            <p>{post.post}</p>
            <input
              type="submit"
              value="削除"
              onClick={() => onClickDelete(post.id)}
            />
            <input
              type="submit"
              value="複製"
              onClick={() => onClickDuplicate(post.id)}
            />
            <input
              type="submit"
              value="編集"
              onClick={() => onClickEdit(post.id)}
            />
            <Modal isOpen={modalIsOpen} ariaHideApp={false}>
              <input
                type="submit"
                value="閉じる"
                onClick={() => setModalIsOpen(false)}
              />
              <div>
                <label>投稿</label>
                <input
                  type="text"
                  id="post"
                  name="post"
                  value={edit.post}
                  onChange={handleEdit}
                />
                <input
                  type="submit"
                  value="送信"
                  onClick={() => onClickUpdate(post.id)}
                />
              </div>
            </Modal>
          </li>
        </ul>
      ))}
    </>
  );
});


..言いたいことは分かりますが今の僕にはこれが限界でした。
いい作り方がひらめいたら都度更新していこうと思います。
ここをもっとこうしたほうがいいなどございましたら教えて下さい!!!

追記:
1度目の修正を行いました。
内容:
1.stateの受け取る型
2.formの値の変え方

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?