学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Django3.2 | 15 | QRオーダーシステムの構築 | 飲食店 表示

[14 | 飲食店登録実装] << [ホーム] >> [16 | 画像アップロード]

Visual Studio Codeで「qrmenu_react」側を編集します。
「src/apis.js」ファイルに記述を追加します。


記述追加 【QRMenu/qrmenu_react/src/apis.js】62〜64行目

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});
}



「styled-components」をインストールします。


コマンド
npm i styled-components@5.2.3 -s


「src/pages/Places.js」ファイルを編集します。


記述編集 【QRMenu/qrmenu_react/src/pages/Places.js】

import { Row, Col } from 'react-bootstrap';
import { React, useEffect, useState, useContext } from 'react';
import styled from 'styled-components';

import { fetchPlaces } from '../apis';
import AuthContext from '../contexts/AuthContext';

import MainLayout from '../layouts/MainLayout';

const Place = styled.div`
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.2s;
    :hover {
        transform: scale(1.05);
    }
    > div {
        background-size: cover;
        height: 200px;
        border-radius: 5px;
    }
    > p {
        margin-top: 5px;
        font-size: 20px;
        font-weight: bold;
    }
`;

const Places = () => {
    const [places, setPlaces] = useState([]);

    const auth = useContext(AuthContext);

    const onFetchPlaces = async () => {
        const json = await fetchPlaces(auth.token);
        if (json) {
            setPlaces(json);
        }
    };

    useEffect(() => {
        onFetchPlaces();
    }, []);
   
    return (
        <MainLayout>
            <h3>登録済み飲食店</h3>
            <Row>
                { places.map((place) => (
                 
                    <Col key={place.id} lg={4}>
                    <Place>
                        <div style={{ backgroundImage: `url(${place.image})` }}></div>
                        <p>{place.name}</p>
                    </Place>
                    </Col>

                ))}
            </Row>
        </MainLayout>
    )
}

export default Places;



ブラウザを確認します。

登録済み飲食店一覧
登録済み飲食店一覧


↓↓クリックして頂けると励みになります。


[14 | 飲食店登録実装] << [ホーム] >> [16 | 画像アップロード]