Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
Apollo Client - useQuery - how to set parameter as optional

I have this query:

const CURRENT_MONTH_BY_USER = gql`
  query getCurrentMonthByUser($selectedMonth: String!, $username: String) {
    getCurrentMonthByUser(selectedMonth: $selectedMonth, username: $username) {
      id
      itemDate
      itemName
      itemCategory
      itemPrice {
        price
        currency
      }
      itemUpdated {
        isUpdated
        updatedBy
        updateStamp
      }
      createdBy {
        username
        name
        date
      }
    }
  }
`

Snippet from component:

  const result = useQuery(CURRENT_MONTH_BY_USER, {
    variables: { selectedMonth, username },
  })

On backend, graphQL query the code is as follows:

    getCurrentMonthByUser: async (_, args) => {
      try {
        const allItems = await Item.find({})

        const items = allItems
          .filter(item => item.itemDate.substring(0, 7) === args.selectedMonth)
          .filter(item => item.createdBy.username === args.username)

        return items
      } catch (err) {
        throw new Error('Specific month not found')
      }
    }

typeDef:

  type Query {
    getCurrentMonthByUser(selectedMonth: String!, username: String): [Item]
  }

My question is, if username is not supplied, the query does not work, returns nothing, how to make the username optional? I didn't set it in the query as required.

My current workaround is to use the Query resolver accordingly, however it's not really ideal in case there'd be more optional parameters

    getCurrentMonthByUser: async (_, args) => {
      try {
        const allItems = await Item.find({})
        let items = []
        if (args.username) {
          items = allItems
            .filter(item => item.itemDate.substring(0, 7) === args.selectedMonth,)
            .filter(item => item.createdBy.username === args.username)
          return items
        }

        items = allItems.filter(
          item => item.itemDate.substring(0, 7) === args.selectedMonth,
        )
        return items
      } catch (err) {
        throw new Error('Specific month not found')
      }
    },

Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

username is optional in your schema definition. The reason you don't get anything back is because the username is undefined when not provided; so the filter can't find anything to return.

This should work:

    getCurrentMonthByUser: async (_, args) => {
      try {
        const allItems = await Item.find({})

        const items = allItems
          .filter(item => item.itemDate.substring(0, 7) === args.selectedMonth)
          .filter(item => args.username ? item.createdBy.username === args.username : true)

        return items
      } catch (err) {
        throw new Error('Specific month not found')
      }
    }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda