Graphql 初体验 第十四章 | #16 Adding Events

对应内容:#16 Adding Events | Build a Complete App with GraphQL, Node.js, MongoDB and React.js

主要内容:

  • 创建一个Event,并展示在当前的event列表中
  • 修复了一个bug
  • 遇到的问题

1 createEvent resolver忘记加入权限判断,并且修复了bug

在这里插入图片描述
在middleware中,修复了一个bug,当前端的拼接的字符串为null的时候,不会转换为空字符,而是一个"null"
在这里插入图片描述

2 完善pages/events.js

import React, { Component } from 'react';
import Modal from '../components/Modal/Modal';
import Dropback from '../components/Dropback/Dropback';
import AuthContext from '../context/auth-context';

class EventsPage extends Component {
    state = {
        isModalShow: false,
        events: []
    }

    static contextType = AuthContext;

    constructor (props) {
        super(props);
        this.titleElRef = React.createRef();
        this.dateElRef = React.createRef();
        this.priceElRef = React.createRef();
        this.descriptionElRef = React.createRef();
    }

    componentDidMount () {
        this.fetchEvents();
    }
    modalStateSwitchHandler = () => {
        this.setState({
            isModalShow: true,
        })
    };

    onCancel = () => {
        this.setState({
            isModalShow: false
        })
    };

    onConfirm = () => {
        const title = this.titleElRef.current.value;
        const date = this.dateElRef.current.value;
        const price = this.priceElRef.current.value;
        const description = this.descriptionElRef.current.value;
        const queryBody = {
            query: `
                mutation {
                    createEvent(eventInput: {title: "${title}", price: ${price}, date: "${date}", description: "${description}"}) {
                        _id
                        title
                        price
                        date
                        description
                        creator {
                            _id
                            email
                        }
                    }
                }
            `
        }
        const token = this.context.token;
        fetch("http://localhost:3030/graphql", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + token
            },
            body: JSON.stringify(queryBody),
        })
        .then(response => {
            if (response.status !== 200 && response.status !== 201) {
                throw new Error("request failed!")
            }
            this.setState({
                isModalShow: false
            })
            return response.json();
        })
        .then(data => {
            this.setState({
            	// contact会返回一个新数组
                events: this.state.events.concat([data.data.createEvent])
            })
        })
        .catch(err => {
            throw err;
        }) ;
    };
    /**
     * fetch all events
     */
    fetchEvents () {
        const queryBody = {
            query: `
                query {
                    events {
                        _id
                        title
                        price
                        date
                        description
                    }
                }
            `
        }
        fetch("http://localhost:3030/graphql", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(queryBody),
        })
            .then((response) => {
                if (response.status !== 200 && response.status !== 201) {
                    throw new Error("request failed!");
                }
                return response.json();
            })
            .then((data) => {
                this.setState({
                    events: data.data.events
                })
            })
            .catch((err) => {
                throw err;
            });
    }
    render() {
        const eventsList = this.state.events.map(event => {
            return <li className="eventlist__item" key={event._id}>{event.title}</li>
        });
        return (
            <React.Fragment>
                {this.state.isModalShow && <Dropback />}
                {this.state.isModalShow && <Modal
                    title="Add an event" 
                    onCancel={this.onCancel}
                    onConfirm={this.onConfirm}
                >
                    <form>
                        <div className="form-control">
                            <label htmlFor="title">Title</label>
                            <input type="text" id="title" ref={this.titleElRef} />
                        </div>
                        <div className="form-control">
                            <label htmlFor="date">Date</label>
                            <input type="datetime-local" id="date" ref={this.dateElRef} />
                        </div>
                        <div className="form-control">
                            <label htmlFor="price">Price</label>
                            <input type="number" id="price" ref={this.priceElRef} />
                        </div>
                        <div className="form-control">
                            <label htmlFor="descrip">Description</label>
                            <textarea id="descrip" rows="4" ref={this.descriptionElRef} >
                            </textarea>
                        </div>
                    </form>
                </Modal>}
                <div>
                    <h1>The events Page</h1>
                    {this.context.token && <button onClick={this.modalStateSwitchHandler}>Add Event</button>}
                </div>
                <div>
                    <ul className="eventlist">{eventsList}</ul>
                </div>
            </React.Fragment>
        );
    }
}

export default EventsPage;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值