为什么在以下代码中收到writetostore错误?

时间:2019-03-05 13:38:57

标签: reactjs graphql react-apollo

我正在尝试在向视频添加评论并收到以下错误的同时进行乐观更新-

writeToStore.js:112 {中缺少字段_id   “ video”:“ 5c7e28fa34238b298846c82e”,   “ user”:“ alex”,   “ comment”:“ 12312”,   “ __typename”:“ Vi

writeToStore.js:112 {   “ video”:“ 5c7e28fa34238b298846c82e”,   “ user”:“ alex”,   “ comment”:“ 12312”,   “ __typename”:“视频”

这是我的相关代码

// Mongoose schema definition
        const VideoCommentSchema = new Schema({
          comment: {
            type: String,
            required: true,
          },
          createdDate: {
            type: Date,
            default: Date.now,
          },
          video: {
            type: String,
            required: true,
          },
          user: {
            type: String,
            required: true,
          },
        });

        module.exports = mongoose.model('VideoComment', VideoCommentSchema);

// Graphql schema type

            type VideoComment {
                _id: ID
                comment: String!
                createdDate: String
                video: String!
                user: String!
            }

// Resolver

            getVideoComments(video: String!): [VideoComment]

            getVideoComments: async (root, { video }, { VideoCommentSchema }) => {
              const videoComments = await VideoCommentSchema.find({ video }).sort({
                createdDate: 'desc',
              });

              return videoComments;
            },


// React-apollo query
            export const GET_VIDEO_COMMENTS = gql`
          query($video: String!) {
            getVideoComments(video: $video) {
              _id
              video
              user
              comment
              createdDate
            }
          }
        `;

// Component that receives video comments

            import React, { Component, Fragment } from 'react';
        import { GET_VIDEO_COMMENTS } from '../../../queries';
        import { Query } from 'react-apollo';
        import CommentItem from '../CommentItem/CommentItem';
        import Error from '../Error/Error';

        import { formatDate } from '../../../utils/utils';

        export default class Comments extends Component {
          render() {
            const { video } = this.props;
            return (
              <Query query={GET_VIDEO_COMMENTS} variables={{ video }}>
                {({ data, loading, error }) => {
                  if (loading) return <div>Loading...</div>;
                  console.log(data);
                  return (
                    <Fragment>
                      {!data.getVideoComments.length && (
                        <p>
                          <strong>
                            У этого видео еще нет комментариев. Добавьте первый.
                          </strong>
                        </p>
                      )}
                      <ul>
                        {error && <Error message={error.message} />}
                        {data.getVideoComments.map(comment => {
                          return (
                            <CommentItem
                              key={comment._id}
                              user={comment.user}
                              date={formatDate(comment.createdDate)}
                              comment={comment.comment}
                            />
                          );
                        })}
                      </ul>
                    </Fragment>
                  );
                }}
              </Query>
            );
          }
        }



// Component that adds video comments, and where I try to update comments related to a video optimistically

        import React, { Component } from 'react';
    import { withRouter } from 'react-router-dom';
    import { Mutation } from 'react-apollo';
    import { ADD_VIDEO_COMMENT, GET_VIDEO_COMMENTS } from '../../../queries';

    import Error from '../Error/Error';
    import withSession from '../../../hoc/withSession';

    const initialState = {
      user: '',
      comment: '',
    };

    class AddComment extends Component {
      state = {
        ...initialState,
      };

      clearState = () => {
        this.setState({ ...initialState });
      };

      validateForm = () => {
        const { comment } = this.state;
        const isInvalid = !comment;
        return isInvalid;
      };

      changeHandler = event => {
        const { name, value } = event.target;
        // console.log([name], value);
        this.setState({
          [name]: value,
        });
      };

      submitHandler = (event, addVideoComment) => {
        event.preventDefault();
        addVideoComment()
          .then(({ data }) => {
            console.log(data);
            this.clearState();
          })
          .catch(err => {
            console.log(err.message);
          });
      };

      updateCache = (cache, { data: { addVideoComment } }) => {
        // console.log(addVideoComment);
        const { video } = this.props;
        const { getVideoComments } = cache.readQuery({
          query: GET_VIDEO_COMMENTS,
          variables: { video },
        });
        cache.writeQuery({
          query: GET_VIDEO_COMMENTS,
          variables: { video },
          data: {
            getVideoComments: [addVideoComment, ...getVideoComments],
          },
        });
      };

      componentDidMount() {
        if (this.props.session.getCurrentUser) {
          const { userName } = this.props.session.getCurrentUser;
          this.setState({
            user: userName,
          });
        }
      }

      render() {
        const { user, comment } = this.state;
        const { video } = this.props;
        return (
          <Mutation
            mutation={ADD_VIDEO_COMMENT}
            variables={{ video, user, comment }}
            update={this.updateCache}>
            {(addVideoComment, { data, loading, error }) => {
              return (
                <div>
                  {error && <Error error={error} />}
                  <form
                    onSubmit={event => this.submitHandler(event, addVideoComment)}>
                    <textarea
                      name='comment'
                      placeholder='Ваш комментарий'
                      cols='30'
                      rows='10'
                      value={comment}
                      onChange={this.changeHandler}
                    />
                    <button type='submit' disabled={loading || this.validateForm()}>
                      Добавить комментарий
                    </button>
                  </form>
                </div>
              );
            }}
          </Mutation>
        );
      }
    }

export default withSession(withRouter(AddComment));

0 个答案:

没有答案