简体   繁体   中英

GraphQL query returns undefined but works fine when I refresh the page?

I am executing a GraphQL query which is fairly complex. Sometimes it returns undefined, but when I refresh the page it works.

I'm building a web application using ReactJS for the frontend, and GraphQL to fetch the data. The query is quite complicated and even when I comment out the entire code in the page (so no information is actually rendered to the page, just they query is executed) , it still sometimes returns undefined.

I've tried the Query in the GraphQL playground and it works fine.

If I look at my server response, the 0.chunk.js.map response time is very long.

Does anyone know what this is likely to be?

The page I am rendering executed 5 different graphQL queries at different levels in the component hierarchy. But it is always the queries in the highest level component that frequently returns undefined.

在此处输入图片说明

在此处输入图片说明

data may be undefined while the query is being fetched from the server. You can provide a default value for it so that the destructuring will work regardless:

({ data: { movie } = {}, error, loading }) => {

You can even access more nested fields using destructuring, but you need to provide a default value at each level. For example:

({ data: { movie: { title } = {} } = {}, error, loading }) => {

Note that data could end up null (as opposed to undefined ) if the request returns an error and it bubbles all the way up to the root. In this case, defaults won't help. But you can still guard against nulls this way:

const movie = data && data.movie

or use something like lodash 's get .

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