Search code examples
javascriptreactjsgraphqlapollo

GraphQL Query - target a specific node - React App


I've created a small app that allows me to build a front-end UI using React on Wordpress. I've managed to create custom posts in Wordpress, which now connect to my app, and the all the data is displaying as I want it to, except for one element.

I'm trying to target the locations name, but I'm not certain how to map through it. I'm trying to display the locations in a p tag, by targeting the edges.node.name. I've tried various ways to get the data, and I've looked at a few solutions on here already, with no luck yet.

import { useQuery } from "@apollo/react-hooks";
import { gql } from "apollo-boost";
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import { Link } from 'react-router-dom';

// get law firm name from locations{ edges { node { name

const POSTS_QUERY = gql`
{
  lawyers(first: 10) {
    nodes { 
      ...LawyerFields
    }
  }
  lawFirms(first: 10) {
    edges {
      node {
        id
        name
        lawFirmId

      }
    }
  }
}

fragment LawyerFields on Lawyer {
  name
  credentials
  profilePhoto {
    mediaItemId
    mediaItemUrl
    altText
    caption
    description
    mediaDetails {
      height
      width
      sizes {
        file
        fileSize
        height
        mimeType
        name
        sourceUrl
        width
      }
    }
  }
  bio
  practicingSince
  locations {
    edges {
      node {
        id
        name
      }
    }
  }
}
`;


function displayContent() {
  /* dangerously set for hiding elements */
  const { loading, error, data } = useQuery(POSTS_QUERY);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error...</p>

  return data.lawyers.nodes.map(({ name, credentials, profilePhoto, bio, practicingSince, locations }) => (

    <div>
      <Container>
        <Row>
          <Col className="backCard">
            <h1 className="titlePost">{name}</h1>
            <p className="credentials">{credentials}</p>
            <img className="workplace" src={profilePhoto.mediaItemUrl} />
            <p className="credentials">Bio</p>
            <p dangerouslySetInnerHTML={{ __html: bio }} className="increaseMargin"></p>
            <p>Practicing since : {practicingSince}</p>
            <Link to="/locations" style={{ textDecoration: 'none' }}>Locations</Link>
            <p>{locations.edges.node.name} I want the locations.name here</p>
          </Col>
        </Row>
      </Container>
    </div>
  ));


}

export default displayContent;

Solution

  • I ended up coming up with the solution myself. I mapped through the locations by adding this into the code.

      {locations.edges.map(({ node }) => {
                  return (
                    <Link key={locations.toString()} to="/locations" style={{ textDecoration: 'none' }}>{node.name}</Link>
                  )
                })}