React

 

Detail.js

import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Container } from "react-bootstrap";

const Detail = () => {
    const { id } = useParams();
    let navigate = useNavigate();

    const [book, setBook] = useState({
        title: '',
        author: ''
    })

    useEffect(() => {
        console.log("id : ", id);
        fetch("http://localhost:8080/book/" + id)
            .then((res) => res.json())
            .then(
                data => {
                    console.log("data : ", data);
                    setBook(data);
                }
            )
            .catch(error => {
                console.log("에러", error);
            });

    }, [])

    const deleteBook = () => {

        fetch("http://localhost:8080/book/" + id, {
            method: "DELETE",
        })
            .then((res) => res.text())
            .then((data) => {
                console.log("data : ", data);
                if (data === "ok") {
                    navigate("/");
                }
            })
            .catch(error => {
                console.log("에러 ", error);
            })
    }

    const updateBook = () => {
        navigate("/updateForm/" + id);
    }


    return (
        <Container>
            <h1>책 상세보기</h1>
            <Button variant='warning' className='me-3' onClick={updateBook}>수정</Button>
            {''}
            <Button variant='danger' onClick={deleteBook}>삭제</Button>
            <hr />
            <h3>저자 - {book.author}</h3>
            <h1>제목 - {book.title}</h1>
        </Container>
    );
};

export default Detail;

 

 

UpdateForm.js

import { useEffect, useState } from 'react';
import { Container, Form, Button } from "react-bootstrap";
import { useNavigate, useParams } from 'react-router-dom';

const UpdateForm = (props) => {
    //const id=props.match.params.id;
    const { id } = useParams();
    let navigate = useNavigate();

    const [book, setBook] = useState({
        title: "",
        author: ""
    });

    const changeValue = (e) => {
        setBook({
            ...book,
            [e.target.name]: e.target.value
        });
    }

    useEffect(() => {
        fetch("http://localhost:8080/book/" + id)
            .then((res) => res.json())
            .then(data => setBook(data))
            .catch(error => {
                console.log("에러 :", error);
            })
    }, []);


    const submitBook = (e) => {
        e.preventDefault(); //submit이 action을 안타고 자기할일을 그만함.
        fetch("http://localhost:8080/book/" + id, {
            method: 'PUT',
            //mode: "cors",
            headers: {
                "Content-Type": "application/json; charset=utf-8"
            },
            body: JSON.stringify(book)
        })
            .then((res) => {
                console.log(1, res);
                return res.json();
            })
            .then(res => {
                console.log(2, res);
                if (res != null) {
                    //props.history.push("/");
                    navigate("/book/" + id);
                } else {
                    alert("책 등록에 실패하였습니다.");
                }
            }).catch(error => {
                console.log("실패", error);
            })
    }


    return (
        <Container>
            <h3 className='mb-5'>수정하기</h3>
            <Form onSubmit={submitBook}>
                <Form.Group className="mb-3" controlId="formBasicEmail">
                    <Form.Label>제목</Form.Label>
                    <Form.Control type="text" placeholder="Enter Title" onChange={changeValue} name="title" value={book.title} />
                </Form.Group>

                <Form.Group className="mb-3" controlId="formBasicEmail">
                    <Form.Label>작성자</Form.Label>
                    <Form.Control type="text" placeholder="Enter Author" onChange={changeValue} name="author" value={book.author} />
                </Form.Group>

                <Button variant="primary" type="submit">
                    수정하기
                </Button>
            </Form>
        </Container>
    );
};

export default UpdateForm;

 

 

 

 

 

 

소스 :  https://github.com/braverokmc79/React-SpringBoot-1/commit/a2f866f97d41474e27b67bd4c877f518e0b2b547

 

 

 

 

 

about author

PHRASE

Level 60  라이트

청년이 다짐해야 할 2가지 과제가 있다. 첫째 속이지 말자. 둘째 놀지 말자. 나는 이것을 어렵게 생각하지 않는다. 우리 청년은 스스로 생각할 때 깨달음을 얻을 수가 있다. -안창호

댓글 ( 4)

댓글 남기기

작성