reactjsreact-hooksreact-bootstrapreact-apollogithub-api-v4

How to map Github GraphQL API commit responses to react-bootstrap Cards?


All the following code is in a custom component titled CommitCards.

Given the following gql query using React Apollo.

const GET_REPO_COMMITS = gql`
query GetRepoCommits($repoName: String!) {
  repository(name: $repoName, owner: "FernandoH-G") {
    defaultBranchRef {
      target {
        ... on Commit {
          history(first: 5) {
            edges {
              node {
                pushedDate
                message
                url
              }
            }
          }
        }
      }
    }
  }
}
`;

const repoName = props.rName
    const { loading, error, data } = useQuery(GET_REPO_COMMITS, {
        variables: { repoName },
    });
    if (loading) return (
        <p>Loading...</p>
    );
    if (error) return (
        <p>Error.</p>
    );

I am able to get the last 5 commits from a given repository belonging to the given owner.

Given by the nature of how GraphQL's JSON response is structured, I feel the need to do the following:

    const commits = data.repository.defaultBranchRef.target.history.edges
    const innerCommits = commits.map(com =>(
        com.node
    ))

Neither mapping over commits or innerCommits using more or less the following react-strap Card code:

    return commits.map(com => {
        <Card 
        key={com.node.url}
        border="info">
            <Card.Body>
                <Card.Header as="h4"> {com.node.pushDate} </Card.Header>
                <Card.Text> {com.node.message}</Card.Text>
            </Card.Body>
        </Card>
    })

renders the cards on the screen.

Note that using the following test html does display the proper information, just as a single long string.

return(
        <p>{commits.map( a => (
            a.node.message
        ))}</p>
    )

The component is called here:

            <CardDeck>
                <CommitCards rName={value} />
            </CardDeck>

Solution

  • So I figured it out...

      return commits.map(com => {
            <Card 
            key={com.node.url}
            border="info">
                <Card.Body>
                    <Card.Header as="h4"> {com.node.pushDate} </Card.Header>
                    <Card.Text> {com.node.message}</Card.Text>
                </Card.Body>
            </Card>
        })
    
    

    should have been this:

      return commits.map(com => (
            <Card 
            key={com.node.url}
            border="info">
                <Card.Body>
                    <Card.Header as="h4"> {com.node.pushDate} </Card.Header>
                    <Card.Text> {com.node.message}</Card.Text>
                </Card.Body>
            </Card>
        ))
    
    

    Note the ( vs the { .