[26 | メニューアイテム更新] << [ホーム] >> [28 | QRコード表示]
削除機能を実装します。
「qrmenu_react/src/apis.js」ファイルに記述を追加します。
記述追加 【QRMenu/qrmenu_react/src/apis.js】99行目
import { toast } from 'react-toastify'; function request(path, {data = null, token = null, method = "GET" }) { return fetch(path, { method, headers: { Authorization: token ? `Token ${token}` : "", "Content-Type": "application/json", }, body: method !=="GET" && method !== "DELETE" ? JSON.stringify(data): null, }) .then((response) => { //もし成功したら if (response.ok) { if(method === "DELETE") { return true; } //toast.success("ログイン成功"); return response.json(); } //失敗 return response.json().then((json) => { //JSONエラー if (response.status === 400) { //toast.error("氏名もしくはパスワードに間違いがあります。"); const errors = Object.keys(json).map( (k) => `${(json[k].join(" "))}` ); throw new Error(errors.join(" ")); } throw new Error(JSON.stringify(json)); }) .catch((e) => { if (e.name === "SyntaxError") { throw new Error(response.statusText); } throw new Error(e); }) }) .catch((e) => { //全エラー toast(e.message, { type: "error" }); }) } export function signIn(username, password) { return request("/auth/token/login/", { data: {username, password}, method: "POST", }) } export function register(username, password) { return request("/auth/users/", { data: {username, password}, method: "POST", }) } export function fetchPlaces(token) { return request("/api/places/", {token}); } export function addPlace(data, token) { return request("/api/places/", {data, token, method: "POST" }); } export function uploadImage(image) { const formData = new FormData(); formData.append("file", image); formData.append("upload_preset", "qrmenu_photos"); return fetch("https://api.cloudinary.com/v1_1/dov57gocw/image/upload", { method: "POST", body: formData, }).then((response) => { return response.json(); }); } export function fetchPlace(id, token) { return request(`/api/places/${id}`, { token }); } export function addCategory(data, token) { return request("/api/categories/", {data, token, method: "POST"}); } export function addMenuItems(data, token) { return request("/api/menu_items/", {data, token, method: "POST"}); } export function updateMenuItem(id, data, token) { return request(`/api/menu_items/${id}`, { data, token, method: "PATCH"}); } export function removePlace(id, token) { return request(`/api/places/${id}`, {token, method: "DELETE"}); } export function removeCategory(id, token) { return request(`/api/categories/${id}`, {token, method: "DELETE"}); } export function removeMenuItem(id, token) { return request(`/api/menu_items/${id}`, {token, method: "DELETE"}); }
「src/pages/Place.js」ファイルを編集します。
記述編集 【/Users/heyjude/Desktop/QRMenu/qrmenu_react/src/pages/Place.js】
import { IoMdArrowBack } from 'react-icons/io'; import { AiOutlineDelete } from 'react-icons/ai'; import { Row, Col, Button, Modal } from 'react-bootstrap'; import { useParams, useHistory } from 'react-router-dom'; import React, { useEffect, useState, useContext } from 'react'; import styled from 'styled-components'; import { fetchPlace, removePlace, removeCategory, removeMenuItem } from '../apis'; import AuthContext from '../contexts/AuthContext'; import MainLayout from '../layouts/MainLayout'; import MenuItemForm from '../containers/MenuItemForm'; import MenuItem from '../components/MenuItem'; const Panel = styled.div` background-color: white; padding: 20px; border-radius: 5px; box-shadow: 1px 1px 10px rgba(0,0,0,0.05); `; const Place = () => { const [place, setPlace] = useState({}); const [menuItemFormShow, setMenuItemFormShow] = useState(false); const [selectedItem, setSelectedItem] = useState(null); const showModal = () => setMenuItemFormShow(true); const hideModal = () => setMenuItemFormShow(false); const auth = useContext(AuthContext); const params = useParams(); const history = useHistory(); const onBack = () => history.push("/places"); const onFetchPlace = async () => { const json = await fetchPlace(params.id, auth.token); if(json) { setPlace(json); } }; const onRemovePlace = () => { const c = window.confirm("本当に削除してもよろしいですか?") if (c) { removePlace(params.id, auth.token).then(onBack); } }; const onRemoveCategory = (id) => { const c = window.confirm("本当に削除してもよろしいですか?") if (c) { removeCategory(id, auth.token).then(onFetchPlace); } }; const onRemoveMenuItem = (id) => { const c = window.confirm("本当に削除してもよろしいですか?") if (c) { removeMenuItem(id, auth.token).then(onFetchPlace); } }; useEffect(() => { onFetchPlace(); }, []); return ( <MainLayout> <Row> <Col lg={12}> <div className="mb-4"> <div className="d-flex align-items-center" Style="margin-left: 2rem; margin-top: 2rem;"> <Button variant="link" onClick={onBack}> <IoMdArrowBack size={25} color="black" /> </Button> <h3 className="mb-0 ml-2 mr-2">{place.name}</h3> <Button variant="link" onClick={onRemovePlace}> <AiOutlineDelete size={25} color="red" /> </Button> </div> </div> </Col> <Col md={4}> <Panel> <MenuItemForm place={place} onDone={onFetchPlace} /> </Panel> </Col> <Col md={8}> {place?.categories?.map((category) => ( <div key={category.id} className="mb-5"> <div className="d-flex align-items-center mb4"> <h4 className="mb-0 mr-2"> <b>{category.name}</b> </h4> <Button variant="link" onClick={() => onRemoveCategory(category.id)}> <AiOutlineDelete size={25} color="red" /> </Button> </div> <br/> {category.menu_items.map((item) => ( <MenuItem key={item.id} item={item} onEdit={() => { setSelectedItem(item); showModal() }} onRemove={() => onRemoveMenuItem(item.id)} /> ))} </div> ))} </Col> </Row> <Modal show={menuItemFormShow} onHide={hideModal} centerd> <Modal.Body> <h4 className="text-center">メニューアイテム</h4> <MenuItemForm place={place} onDone={() =>{ onFetchPlace(); hideModal() }} item={selectedItem} /> </Modal.Body> </Modal> </MainLayout> ) }; export default Place;
「src/components/MenuItem.js」ファイルの編集をします。
記述編集 【QRMenu/qrmenu_react/src/components/MenuItem.js】
import {Col, Button } from 'react-bootstrap'; import React from 'react'; import styled from 'styled-components'; import { BiEdit } from 'react-icons/bi'; import { AiOutlineDelete } from 'react-icons/ai'; const Container = styled.div` border-radius: 5px; background-color: white; margin-bottom: 30px; box-shadow: 1px 1px 8px rgba(0,0,0,0,1); display: flex; opacity: ${({active}) => (active ? 1 : 0.6)}; > div: first-child { width: 40%; border-top-left-radius: 5px; border-bottom-left-radius: 5px; background-size: cover; } > div:last-child { padding: 15px 20px; min-height: 150px; } `; const MenuItem = ({ item, onEdit, onRemove }) => ( <Container active={item.is_available}> <Col xs={5} style={{ backgroundImage: `url(${item.image})` }} /> <Col xs={7} className="d-flex flex-column justify-content-between w-100"> <div> <div className="d-flex justify-content-between align-items-center mb-2"> <h4 className="mb-2"> <b>{item.name}</b> </h4> <span> { onEdit ? ( <Button variant="link" onClick={onEdit}> <BiEdit size={20} /> </Button> ) : null } { onRemove ? ( <Button variant="link" onClick={onRemove}> <AiOutlineDelete size={20} color="red" /> </Button> ) : null } </span> </div> <p className="mb-4">{item.description}</p> </div> <div className="d-flex justify-content-between align-items-end"> <div> <h5 className="mb-0 text-standard"> <b>{item.price}円</b> </h5> </div> {!item.is_available ? (<big className="text-danger">品切れ</big>) : null} </div> </Col> </Container> ); export default MenuItem;
削除機能が実装されました。
↓↓クリックして頂けると励みになります。
[26 | メニューアイテム更新] << [ホーム] >> [28 | QRコード表示]