aws-amplify-react Connect returns undefined data first

时光怂恿深爱的人放手 提交于 2019-12-13 14:58:50

问题


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>
      )
    }
}



回答2:


See AWS API LINK

Relevant code snippet from above link:

<Connect query={graphqlOperation(queries.listTodos)}>
            {({ data: { listTodos }, loading, error }) => {
                if (error) return (<h3>Error</h3>);
                if (loading || !listTodos) return (<h3>Loading...</h3>);
                return (<ListView todos={listTodos.items} /> );
            }}
        </Connect>

Notice that the inside of the Connect component comes with not just 'data', but also 'error' and 'loading'. Since this is an asynchronous request, if you try to return data immediately, it will not be there, but if you do as the example above shows (assuming your request returns data of course), you should be good.



来源:https://stackoverflow.com/questions/50607532/aws-amplify-react-connect-returns-undefined-data-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!