1
votes

My GraphQLServer query:

query  {
  sources {
    name
    id
  } 
}

returns array of objects like so:

{
  "data": {
    "sources": [
      {
        "name": "bootstrap.css",
        "id": 1
      },
      {
        "name": "normalize.css",
        "id": 2
      }
    ]
  }
}

Trying to understand how to call it from React (redux). I tried:

function mapQueriesToProps( {ownProps, state}) {
 return {
   data: {
     query: gql`
      query {
        sources {
         id
         name
        }
      }
   `,
   forceFetch: false,
   returnPartialData: false,
  },
 };
};

But nothing happens. Just get loading: true. I'm using apollo-client and got it all wired up according to docs (I think). By that I mean I'm using connect(mapQueriesToProps) etc.

  • When does the query actually get run?
  • Does it automatically get run when component loads?
  • Is there a step I need to do to wait for data to return?
  • How does the component know to wait for the data?
  • Is it alright to return an array? I couldn't find any examples of returning an array in the docs.
  • I only want to run this once, not do any polling or anything. Is that the only way?

This is my first test of Apollo. Any guidance appreciated, because the docs are rather skimpy for beginners.

2

2 Answers

0
votes

Have you tried naming the query? I.e. writing query abc { instead of just query {. If that fixes the problem, you should file an issue on react-apollo.

If it doesn't work, you can start narrowing down the error by checking if there are any errors in the console and checking in the network tab if the browser actually makes a request.

0
votes

Strangely, this 1st method works for me...

Assuming:

import gql from 'graphql-tag';
import { graphql } from 'react-apollo';

You might just be able to (e.g):

const getSources = gql`
  query {
    sources {
     id
     name
    }
  }
`;

export default graphql(getSources) (connect(mapStateToProps, mapDispatchToProps)(YouContainer));

YouContainer props.data will have your query result.

And this 2nd method, also works (probably the best approach):

const getSources = graphql(gql`
   _your_query_here_
`);

const connector = connect(mapStateToProps, mapDispatchToProps);
export default connector(getSources(YourContainer));

And as @helfer mentioned, you should name your query also.