aws-amplify-react Connect returns undefined data f

2019-07-17 15:47发布

问题:

I have the following setup:

  • aws-amplify-react
  • appsync
  • create-react-app

and following this documentation: https://aws.github.io/aws-amplify/media/api_guide#connect

As in the doc, rendering this gives me 2x undefined data before returning the correct data. This breaks the app, as nested fields (in my example, e.g. getRoom.id) cannot be accessed.

Component example:

export const AppSyncTest = () => (
  <Connect query={graphqlOperation(query)}>
    {({ data: { getRoom } }) => {

      console.log(getRoom); // returns undefined 2x before data is there

      if (!getRoom) { // without this, app breaks
        return 'why? (can even happen if loading is false)';
      }

      return (
        <div className="App">
          <header className="App-header">
            <h1 className="App-title">Welcome to IntelliFM WebApp</h1>
          </header>
          <p className="App-intro">
            Found room {getRoom.id} with label {getRoom.label} and description{' '}
            {getRoom.description}
          </p>
        </div>
      );
    }}
  </Connect>
);

回答1:

I got the same issue, I think amplify is expecting developer to check if the response is Ready. I solved it by:

<Connect query={graphqlOperation(someAppSyncQuery)}>
  {this.test}
</Connect>


const test = (appSyncResponseObject: any): any => {
  if (appSyncResponseObject.data == null ||
      appSyncResponseObject.data.getRecords == null) {
      return null;
    } else {
      const records = appSyncResponseObject.data.getRecords;
      return (
        <div>
          <h3>List all records</h3>
          <ul>
            {records.map(
              (records) =>
                (<li key={records.uuid}>{records.context}</li>)
            )
            }
          </ul>
        </div>
      )
    }
}