0

Data:

[
  {
    "name": "Gates of Olympus",
    "slug": {
      "_type": "slug",
      "current": "gates-of-olympus"
    }
  },
  {
    "name": "Floating Dragon",
    "slug": {
      "_type": "slug",
      "current": "floating-dragon"
    }
  },
  {
    "name": "Buffalo King Megaways",
    "slug": {
      "_type": "slug",
      "current": "buffalo-king-megaways"
    }
  },
  {
    "name": "Fruit Party",
    "slug": {
      "_type": "slug",
      "current": "fruit-party"
    }
  }
]

How do I query only objects with slug gates-of-olympus ?

Code:

export const getServerSideProps = async ({params}:any) => {
    
    const query = `*[_type=="game"]{
    name,
    slug,
    }`;
  
    const games = await sanityClient.fetch(query);
  
    return {
      props: {
        games,
      },
    };
  };

slug is obtained through context (params.game).

I also tried,

*[_type=="game" && slug.current == ${params.game}] but still returns all data.
Sai Krishnadas
  • 2,863
  • 9
  • 36
  • 69
  • It seems strange that `*[_type=="game" && slug.current == ${params.game}]` returns all documents. What does `*[_type=="game" && slug.current != ${params.game}]` return? – Geoff Ball Jun 28 '22 at 19:13

2 Answers2

1

Wrap ${params.game} with the quotes. Like this "${params.game}". It will work

Ikramzv
  • 31
  • 4
0

You get back all the data but the first one or first item in that array of data is the one your searching for so at the end of your query put [0] at the end to get the first value you should be solid eg *[_type=="game" && slug.current == '${params.game}'][0]

Ref go to this video which is taught by js mastery skip to 1:21:27 he starts explaining how to get the current slug/product https://www.youtube.com/watch?v=4mOkFXyxfsU&t=5153s