GraphQL Inline fragments check if exist and then output in a .map

这一生的挚爱 提交于 2020-01-22 03:10:00

问题


I have a react component in gatsbyJS that is mapping through a graphQL query, so far it works however I have introduced a inline fragment in the graphQL query two of them actually and I want to check if fragment exists then output the code otherwise all my maps are outputting empty div's after real content is outputted. I didn't include the whole query or all the code for brevity.

Hopefully someone can help, Thanks!

Here is my map and jsx

{data.datoCmsProject.projectBlock.map(projectEntry => { 

        return (  

          <>

          // I want to check here if    DatoCmsProjectBlockGrid fragment exists then render below       

          <BlockGridWrapper>
            <BlockGrid key={projectEntry.id}>

                <div>{projectEntry.titleOfGridSection}</div>
            </BlockGrid>
          </BlockGridWrapper>

        // end check for DatoCmsProjectBlockGrid

        // I want to check here if DatoCmsSingleProjectBlockContent fragment exists, then render below

         <NewBlock key={projectEntry.id}> 

          <img key={imageEntry.originalId} src={imageEntry.url}/>

         </NewBlock>

        //end check for DatoCmsSingleProjectBlockContent

...

Here is my query

projectBlock{
        ... on DatoCmsSingleProjectBlockContent {
            id
            titleOfSection
            descriptionOfImage
            descriptionToggle
            wideView
            imageTextSide
            imageAssetHideShow
            imageAsset{
              url
              originalId
            }
          }
        ... on DatoCmsProjectBlockGrid {
          id
          titleOfGridSection
        }
      }   

回答1:


You can utilize the __typename field to determine the type of the returned object and then render the appropriate component.

projectBlock {
  __typename
  ... on DatoCmsSingleProjectBlockContent {
    id
    # other fields
  }
  ... on DatoCmsProjectBlockGrid {
    id
    # other fields
  }
}   

In this case, __typename will resolve to DatoCmsSingleProjectBlockContent, DatoCmsProjectBlockGrid or whatever other possible types for the projectBlock field. If there are other possible types that you don't want to render, you should either filter the array first or utilize reduce instead of map to the same effect:

data.datoCmsProject.projectBlock
  .filter(({ __typename }) => __typename === 'DatoCmsSingleProjectBlockContent' || __typename === 'DatoCmsProjectBlockGrid')
  .map(projectEntry => {
  if (projectEntry.__typename === 'DatoCmsSingleProjectBlockContent') {
    return <BlockGridWrapper/>
  }
  return <NewBlock/>
})


来源:https://stackoverflow.com/questions/59585841/graphql-inline-fragments-check-if-exist-and-then-output-in-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!