vasansr / pro-mern-stack-2

Code listing for the book Pro MERN Stack, 2nd Edition
https://www.apress.com/book/9781484243909
329 stars 190 forks source link

GraphQL's query error in loadData() from IssueDetail.jsx #4

Closed AnhHuy02 closed 4 years ago

AnhHuy02 commented 4 years ago

When using a new GraphQL version and click the "Select" button from the issues, an error was showed in the command line like this below: image

When I checked your code, I found that in the IssueDetail.jsx, at the loadData function, you write the query like this:

const query = `query issue($id: Int!) {
      issue (id: $id) {
        id description
      }
}`;

To fix this, you need to change the query syntax into:

const query = `query { issue(id: ${id}) {
      id description
    }
}`;

This will show the issue's description and fix the GraphQL error when using a newer version (my version was 14.4.2 and your was 0.13.2).

TinMiner commented 4 years ago

I've tried changing the syntax for the query in the edit file, but still the same error.

edward-hong commented 4 years ago

@TinMiner I was able to fix this by changing the props this.props.match.params.id into an integer with parseInt. Here is my code for the entire loadData method:

async loadData() {
    const {
      match: {
        params: { id },
      },
    } = this.props
    const query = `query issue($id: Int!) {
      issue(id: $id) {
        id
        description
      }
    }`

    const data = await graphQLFetch(query, { id: parseInt(id, 10) })  // <----- note here
    if (data) {
      this.setState({ issue: data.issue })
    } else {
      this.setState({ issue: {} })
    }
  }

The GraphQL Schema wants an integer instead of a string so before making fetch request I turned the variable into an integer that the API accepts. Hope this helps.

Edit: It's better to use parseInt(id, 10) instead of parseInt(id) as the latter will cause an error with the linting configuration