Take a value from an array, match it with with the value in array from React State and use it in graphql query

Issue

This Content is from Stack Overflow. Question asked by xxxbud

I have a search bar for finding products. The problem is I would like to have an access to categories (in the index page (first render)) filtered by tags which comes from graphql query.
I’d like to fetch all products paginated in home page, but if I click a button which will change the state tags to ['all', 'sugar'] it should fetch only the products with tags array which contains ['all', 'sugar'] but the problem is I’d like to fetch all products which have in tags array a value all in the [0] index of this array.
I got react state:
const [tags, setTags] = useState(['all']);
Is it possible to take the first value all from an array ['all', 'sugar'] and use it in graphql query to fetch all products in the first render?

const { data, error } = useSWR(
    [
      process.env.NEXT_PUBLIC_GRAPHCMS_ENDPOINT,
      `
         query getSugars($searchValue: String $skip: Int $tags: [String!]) {
        sugarsConnection(orderBy: createdAt_DESC, where: {title_contains: $searchValue, tags: $tags}, first: 6, skip: $skip) {
          edges {
            node {
              title
              tags
              description {
                raw
              }
              id
              slug
              coverImage {
                url
              }
              price
              brand
              stock
              isNewProduct
              isOnDiscount
              discountValue
            }
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
            
          }
        }
      }
      
      
      
  `,
      searchValue,
      skip,
      tags,
    ],
    (endpoint, query) => fetcher(endpoint, query, { searchValue, skip, tags }),
    {
      fallbackData: sugars,
      revalidateOnFocus: true,
    }
  );



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?