skip to Main Content

Apollo Client Query

`export const GET_PROJECT = gql`
  query singleProject($projectId: ID!) {
    getProject(projectId: $projectId) {
      _id
      name
      description
      status
    }
  }
;``

useQuery


const { projectId } = useParams();

  const { loading, error, data } = useQuery(GET_PROJECT, {
    variables: { projectId : projectId },
  });

  const project = data?.project || {};

Query works fine in Apollo Sandbox as per below

{
  "data": {
    "getProject": {
      "_id": "6595f304af46ebccba110bd0",
      "name": "New prroject",
      "description": "HTML & CSS",
      "status": "planning"
    }
  }
}

getting 400 Bad Request and response with an error errors : [{message: "Variable "$projectId" of required type "ID!" was not provided.",…}] What could be the problem – any help??

Code works on backend and can fetch data in Apollo Sandbox but not able to figure out the reason for required type ID was not provided when I try to run it useQuery.

2

Answers


  1. Chosen as BEST ANSWER

    I over complicated situation - so I simplified the process - I give project detail page route of "project/:id" than I was able to get projectId by using UseParams hooks. Bellow the the code that worked for me - wasn't anything difference.

    const { id } = useParams();
      const { loading, error, data } = useQuery(GET_PROJECT, {
        variables: { projectId: id },
    });
    

    Thanks !!


    1. First check if projectId is undefined.
        useEffect(() => {
            console.log('projectId=', projectId);
        }, [projectId]);
    
    1. The $projectId is required, so you can skip executing query when project id is undefined.
        const { loading, error, data } = useQuery(GET_PROJECT, {
            variables: { projectId : projectId },
            skip: !projectId,
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search