简体   繁体   中英

Use data from graphql response in React

I guess this is a simple issue, but I am stuck here for a while, so any advice may be helpful!

I have a react app and I am calling a GraphQL api (with apollo). Inside an arrow function component I have:

const [executeQuery, { data }] = useLazyQuery(GET_ALL_TASKS);

const findId = (step) => {
    executeQuery({
      variables: {
        "query": {
          "state": "CREATED",
          "taskDefinitionId": "something"
      }
     }
    })
  }

The query is successful and in the browser inspect panel I get this as the graphql response:

{
  "data" : {
    "tasks" : [ {
      "id" : "2251",
      "name" : "some_name",
      "__typename" : "Task"
    } ]
  }
}

In my code I want to use the retrieved id . How can I isolate the id from the response? When I am trying to access the data I get an undefined error. Thank you!

Not sure why you are wrapping your executeQuery in a function.

The data will be part of the response so you can get it like this:

const {data, loading} = executeQuery({
  variables: {
    "query": {
       "state": "CREATED",
       "taskDefinitionId": "something"
     }
   }
})

// may also need to check for the error state
if(loading){
  console.log("Loading...")
}else{
  /// the ids seem to be an array of objects
  const ids = data.tasks.map((task)=> task.id)
  console.log(ids)
}

For anyone who may have the same problem, I realized it is a caching error happening in apollo client. I couldn't figure out the solution. However, I temporarily solved it by downgrading the apollo client dependency to version 3.2.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM