Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 55 additions & 11 deletions js/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,8 @@ class App extends React.Component {

return (
<Connect query={graphqlOperation(ListEvents)}>
{({ data: { listEvents } }) => (
<ListView events={listEvents.items} />
{({ data: { listEvents }, loading }) => (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do something a little more comprehensive that also includes error checking like so:

<Connect query={graphqlOperation(ListEvents)}>
  {({ data: { listEvents }, loading, error }) => (
    if (error) return <h1>Error fetching results</h1>
    if (loading || !data) return <h1>Loading...</h1>
      return <ListView events={listEvents.items} />
  )}
</Connect>

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For sure, I will try this and update the docs. Thanks!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the functioning snippet in JSX:

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

!loading && <ListView events={listEvents.items} />
)}
</Connect>
)
Expand All @@ -461,8 +461,8 @@ Also, you can use `subscription` and `onSubscriptionMsg` attributes to enable su
onSubscriptionMsg={(prev, { subscribeToEventComments }) => {
console.log ( subscribeToEventComments);
return prev; }}>
{({ data: { listEvents } }) => (
<AllEvents events={listEvents ? listEvents.items : []} />
{({ data: { listEvents }, loading }) => (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to the above, let's be more prescriptive on the error handling and also call out the function argument from the GraphQL response. Here is a suggestion for the code and text:

        <Connect query={graphqlOperation(ListTodos)}
          subscription={graphqlOperation(OnCreateTodo)}
          onSubscriptionMsg={(prev, {onCreateTodo}) => {
              console.log('Subscription data:', onCreateTodo)
              return prev;
            }
          }>
        {({ data: { listTodos }, loading, error }) => {
          if (error) return <h1>Error</h1>;
          if (loading || !listTodos) return <h1>Loading...</h1>;
            return <ListView todos={listTodos.items} />
        }}
        </Connect>

Note - In the above example OnCreateTodo passed to the subscription prop as subscription={graphqlOperation(OnCreateTodo)} is the name of your GraphQL document. For example when used with the Amplify CLI it will generate a document and you would use import { OnCreateTodo } from './graphql/subscriptions'; at the top of your app code. However the argument onCreateTodo received by the onSubscriptionMsg is defined in the GraphQL selection set. For example your GraphQL statement would look like the following here:

export const OnCreateTodo = `
  subscription OnCreateTodo {
    onCreateTodo {
      id
      name
      description
    }
  }
`;

!loading && <AllEvents events={listEvents ? listEvents.items : []} />
)}
</Connect>

Expand All @@ -471,16 +471,60 @@ Also, you can use `subscription` and `onSubscriptionMsg` attributes to enable su
For mutations, a `mutation` function needs to be provided with `Connect` component. `mutation` returns a promise that resolves with the result of the GraphQL mutation.

```js
class CreateEvent extends React.Component {
// ...
// This component calls its onCreate prop to trigger the mutation
// const variables = { id: '1' }
// this.props.onCreate(variables)
// ...
class CreateEventView extends React.Component {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe since this is an example we can simplify it a bit so that new customers to React don't get lost on the extra state management here for handling input. Also, we should show the input type since that's what we're doing with our coegen. Suggested simplification which builds upon the last example:

class AddTodo extends Component {
  constructor(props) {
    super(props);
    console.log(props);
  }

  submit = async () => {
    const { onCreate } = this.props;
    var input = {
      name: 'TEST',
      description: 'TEST'
    }
    console.log(input);
    await onCreate({input})
  }

  render(){
    return (
      <button onClick={this.submit}>Click</button>
    );
  }
}

class App extends Component {
  render() {

    const ListView = ({ todos }) => (
      <div>
          <h3>All Todos</h3>
          <ul>
            {todos.map(todo => <li key={todo.id}>{todo.name}</li>)}
          </ul>
      </div>
    )

    return (
      <div className="App">
        <Connect mutation={graphqlOperation(CreateTodo)}>
          {({mutation}) => (
            <AddTodo onCreate={mutation} />
          )}
        </Connect>

        <Connect query={graphqlOperation(ListTodos)}
          subscription={graphqlOperation(OnCreateTodo)}
          onSubscriptionMsg={(prev, {onCreateTodo}) => {
              console.log('Subscription data:', onCreateTodo)
              return prev;
            }
          }>
        {({ data: { listTodos }, loading, error }) => {
          if (error) return <h1>Error</h1>;
          if (loading || !listTodos) return <h1>Loading...</h1>;
            return <ListView todos={listTodos.items} />
        }}
        </Connect>
      </div>

    );
  }
}


constructor(props) {
super(props);

this.state = this.getInitialState();
}

getInitialState() {
return {
name: '',
where: '',
when: new Date().toISOString(),
description: '',
};
}

handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
}

handleSubmit = async () => {
const { name, where, when, description } = this.state;
const { onCreate } = this.props;

try {
await onCreate({ name, where, when, description });
} catch (error) {
console.error(error);
}

this.setState(this.getInitialState());
}

render() {
const { name, where, when, description } = this.state;

return (
<div onSubmit={this.handleSubmit}>
<div>
<label>Create event</label>
<div><label>Name</label> <input type="text" name="name" value={name} onChange={this.handleChange} /></div>
<div><label>Where</label> <input type="text" name="where" value={where} onChange={this.handleChange} /></div>
<div><label>When</label> <input type="text" name="when" value={when} onChange={this.handleChange} /></div>
<div><label>Description</label><input type="text" name="description" value={description} onChange={this.handleChange} /></div>
<button onClick={this.handleSubmit}>Create</button>
</div>
</div>
);
}
}
<Connect mutation={graphqlOperation(Operations.CreateEvent)}>
{({ mutation }) => (
<CreateEvent onCreate={mutation} />
<CreateEventView onCreate={mutation} />
)}
</Connect>
```
Expand Down