0
votes

I am having troubles with a mutation in graphQL apollo. When a page loads, it will run a query lectureResponseQuery and if the query == null a mutation fetchLectureResponseMutation is run to create a new document. This mutation returns the new result and I do an update to the query and I expect that the component will re-render with the new data, but it doesn't. Does anyone know why that is? Thanks!

@graphql(fetchLectureResponseMutation, {
  options: ownProps => ({
    variables: { lectureName: ownProps.match.params.lectureName },
    update: (proxy, { data: { fetchLectureResponse } }) => {
      const data = proxy.readQuery({
        query: lectureResponseQuery,
        variables: { lectureName: ownProps.match.params.lectureName },
      });
      data.lectureResponse = fetchLectureResponse;
      proxy.writeQuery({
        query: lectureResponseQuery,
        data,
      });
    },
  }),
  name: 'fetchLectureResponse',
})
@graphql(lectureResponseQuery, {
  options: ownProps => ({
    variables: { lectureName: ownProps.match.params.lectureName },
  }),
})
class LecturePage extends React.PureComponent {
  componentWillUpdate(nextProps) {
    if (nextProps.data.lectureResponse === null) {
      this.props.fetchLectureResponse();
    }
  }


  render() {
    const { data } = this.props;
    if (data.loading || data.lectureResponse === null) {
      return <Loading />;
    }

    return <LectureLayout lectureResponse={data.lectureResponse} />
  }
}
1

1 Answers

0
votes

For anyone looking into this issue in the future- the central issue is that I wanted to do a find OR create operation. This works much better when the query just returns the new object if it doesn't exist because then you only make 1 backend call which means that you don't have to synchronize the timings between a query and a mutation.

TLDR: Use a query for a findOrCreate operation!