Can I use nested properties as variables while using useQuery from Apollo and GraphQL?

Can I use nested properties as variables while using useQuery from Apollo and GraphQL?


0

I created a MERN application using Graphql, and I’m trying to fetch using properties that are nested inside my data as variables. As an example, I have client and project models. Is it possible to fetch all the projects for a specific client by passing the client ID when fetching the projects with useQuery. Code examples are included. I removed import statements for succinctness. Also, I have the client.id (named clientId) available as a param in the url.

COMPONENT THAT CALLS USEQUERY

export const ClientProjects = () => {
  const { clientId } = useParams();

// variable set up is incorrect but gives an idea of what I'm trying to do
  const { loading, error, data } = useQuery(GET_PROJECTS, {
    variables: { id: { client: { id: clientId } } },
  });

  if (loading) return <p>Loading...</p;
  if (error) return <p>There was an error...</p>;

  return (
    <>
      {data.projects.map((project) => (
        <ProjectCard key={project.id} project={project} />
      ))}
    </>
  );
};

CLIENT EXAMPLE

id: 64f6081cf3af0aa2cfb57d62
firstName: "Bob"
lastName: "Barker"

PROJECT EXAMPLE

id: "64f677e0590bfbf82793407e",
title: "Company Website",
client: {
   id: "64f6081cf3af0aa2cfb57d62",
   firstName: "Bob", 
   lastName: "Barker"
}

PROJECT SCHEMA

// Project Type
const ProjectType = new GraphQLObjectType({
  name: "Project",
  fields: () => ({
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    client: {
      type: ClientType,
      resolve(parent, args) {
        return Client.findById(parent.clientId);
      },
    },
  }),
});

PROJECT QUERY

import { gql } from "@apollo/client";

const GET_PROJECTS = gql`
  query getProjects {
    projects {
      id
      title
      client {
        id
        firstName
        lastName
      }
    }
  }
`;

1 Answer
1


0

That entirely depends on what your Server Schema accepts as arguments for the Query field you call in your actual GraphQL query.

Without knowing your Schema and Query, the questions cannot really be answered – all I can say that if your Schema isn’t explicitly designed to accept arguments like this, it’s very unlikely unless you can change the server side implementation to match your frontend code.

1

  • I updated with my query and my schema for the project. Currently, my project find method uses the client ID.

    – jonteal

    1 hour ago



Leave a Reply

Your email address will not be published. Required fields are marked *