如何将Redux Saga与AWS Amplify结合使用?

时间:2019-07-22 05:53:08

标签: null this redux-saga aws-amplify

我正在尝试通过Redux Saga使用AWS Amplify的辅助方法进行API调用。

import { API, graphqlOperation } from 'aws-amplify';
import * as R from 'ramda';
import { call, put } from 'redux-saga/effects';

import { listQuestions } from '../graphql/queries';
import { openSnackbar } from '../snackbar/snackbar-reducer';
import { addQuestions, fetchQuestions as fq } from './question-reducer';

const toAction = R.pipe(
  R.path(['data', 'listQuestions', 'items']),
  addQuestions
);

function* fetchQuestions() {
  try {
    const result = yield call(
      API.graphql,
      graphqlOperation(listQuestions, { limit: 100 })
    );
    yield put(toAction(result));
  } catch (e) {
    console.log(e);
    yield put(openSnackbar(e.message));
  }
}

如您所见,我正在使用AWS Amplify的JS框架部分中的API.graphqlgraphqlOperation帮助方法。

但是,这总是会引发错误:

TypeError: Cannot read property '_graphql' of null
    at APIClass.graphql (API.js:831)

APIClass.graphql处给定的代码如下:

APIClass.prototype.graphql = function (_a) {
    var paramQuery = _a.query, _b = _a.variables, variables = _b === void 0 ? {} : _b, authMode = _a.authMode;
    var query = typeof paramQuery === 'string' ? parser_1.parse(paramQuery) : parser_1.parse(printer_1.print(paramQuery));
    var _c = query.definitions.filter(function (def) { return def.kind === 'OperationDefinition'; })[0], operationDef = _c === void 0 ? {} : _c;
    var operationType = operationDef.operation;
    switch (operationType) {
        case 'query':
        case 'mutation':
            return this._graphql({ query: query, variables: variables, authMode: authMode });
        case 'subscription':
            return this._graphqlSubscribe({ query: query, variables: variables, authMode: authMode });
    }
    throw new Error("invalid operation type: " + operationType);
};

为什么这里的thisnull?是否可以使用带有Redux Saga的AWS Amplify中的GraphQL helper方法?

1 个答案:

答案 0 :(得分:0)

找到解决方案。您需要向this提供call context

yield call([API, 'graphql'], graphqlOperation(listQuestions, { limit: 100 }))