2
votes

I'm new to Apollo GraphQL. When reading its docs, it mentioned the word imperative several times. But I can't really find an explanation online that clarify what exactly "imperative" does for Apollo GraphQL. So far, the easiest def. I got is imperative programming is like how you do something, and declarative programming is more like what you do.

Here is an example of mentioning imperative for Apollo GraphQL:

GraphQL’s mutations are triggered imperatively, but that’s only because a HOC or render prop grants access to the function which executes the mutation (e.g. on a button click). With Apollo, the mutations and queries become declarative over imperative.

Could someone provide a solid example to help me understand what imperative mean in Apollo GraphQL?

1

1 Answers

0
votes

It's actually a simpler paragraph than you realise, in this sentence imperative is explaining how one might choose to write out a graphql react component as:

import React from 'react';
import { Query } from 'react-apollo';

const Profile = () => (
  <Query query={}>
    {() => <div>My Profile</div>}
  </Query>
);

export default Profile;

While this component doesn't actually make a query because no query is provided we are imperatively programming it. Imperative in the sense we are providing the query into the component and the HOC triggers the query or mutation and passes it into the props. In this example we can step through the code from creating the HOC and adding a query to calling it via props on the component. Though it's interesting to note that a GraphQL query on it's own is declarative in nature.

Declarative is best characterised as describing what we would like and in the apollo client the best way to visualize this is through a functional component.

const LAST_LAUNCH = gql`
  query lastLaunch {
    launch {
      id
      timestamp
    }
  }
`;

export function LastLaunch() {
  const { loading, data } = useQuery(LAST_LAUNCH);
  return (
    <div>
      <h1>Last Launch</h1>
      {loading ? <p>Loading</p> : <p>Timestamp: {data.launch.timestamp}</p>}
    </div>
  );
}

In this example you can see we are essentially executing this query / mutation using

const { loading, data } = useQuery(LAST_LAUNCH);

This line of code describes using the query written above what we would like to be returned making it a declarative statement.

In simplistic terms the HOC component in example one has several steps that you can follow before you could use your data. In the second example we are simply describing what we would like in a single statement and receiving back the data.

Finally it's also important to mention that in programming we generally have a mixture of imperative and declarative statements / blocks of code throughout our application and it's perfectly normal.