Search code examples
javascriptreactjsgraphqlfrontendapollo

How can I pass useQuery variable from component prop?


I have this query :

const GET_ANALYTICS = gql`
  query($courseId: String) {
    getStudentsAnalytics(courseId: $courseId) {
        totalStudents,
        studentsNotStartedCoursesYetPercentage,
        studentsFinishedCoursesPercentage,
        studentsInProgressCoursesPercentage,
        studentsCompletedQuizzesPercentage,
        studentsFailedQuizzesPercentage,
        studentsInProgressQuizzesPercentage
    }
}
`

and in the code am trying to pass variable from component prop:

const AnalyticsStatistic = (courseId: string) => {

  const { loading, error, data } = useQuery(GET_ANALYTICS){
   variables: {courseId},
 }

for red underlined param courseId am getting these errors:'courseId' is declared but its value is never read.ts(6133) Duplicate identifier 'courseId'.ts(2300)

and for inside variable: {courseId} am getting these errors:Duplicate identifier 'courseId'.ts(2300) Binding element 'courseId' implicitly has an 'any' type.ts(7031)

for inside courseId

for outside courseId

problems in console


Solution

  • your GET_ANALYTICS query is like this, so you don't have to pass the courseId inside an object check the code below

    const GET_ANALYTICS = gql`
      query($courseId: String) {
        getStudentsAnalytics(courseId: $courseId) {
            ....
        }
    }
    `
    

    the corresponding useQuery hook should be used like this and make the courseId argument to string instead of any because query is expecting a string

    const AnalyticsStatistic = (courseId: string) => {
                                               //? FIX 
     const { loading, error, data } = useQuery(GET_ANALYTICS,{
      variables: {courseId},
    })
    

    if you are getting unused variable, then add this inside tsconfig.json

    {
      "compilerOptions": {
        "noUnusedLocals": false,
        "noUnusedParameters": false
      }
    }