reactjsnext.jssanitygroq

How to use query param as a variable in groq sanity query inside getServerSideprops in next js?


I'm trying to implement search fuctionality in my blog project but facing problem in using variable in groq query(sanity) inside getServersideprops.

Here is my code

import React from 'react'
import { useRouter } from 'next/router'
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import Banner from '../../components/Banner'
import Header from '../../components/Header'
import { sanityClient,urlFor } from '../../sanity'
import { Post } from '../../typings'
import PostCard from '../../components/Post'
import Footer from '../../components/Footer'
import BottomNav from '../../components/BottomNav'

interface Props{
  posts:[Post];
}

export default function Search({ posts}:Props) {
 
    
  return (
    <>
    <div className='max-w-6xl mx-auto container-fix md:mb-1 '>
      <Head>
        <title>Const - Read for free</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
        <Header/>
        <Banner/>
        <PostCard posts={posts} />
        <Footer/>     
      
    </div>
    <BottomNav />
    </>
  )
}



export const getServerSideProps = async(context:any)=>{
  const search = context.query.url;
  const query = `
                  *[_type=="post" && title == $search]{
                  _id,
                  title,
                  author -> {
                  name,
                  image,
                  
                },
                _createdAt,
                description,
                mainImage,
                category,
                slug
                }`;
  const posts = await sanityClient.fetch(query);
 
  return {
    props:{
      posts
      
    }
  }
}

this is the error im getting

**Server Error ClientError: param $search referenced, but not provided **

but when the variable is repalced with actual string then I'm geeting results succesfully.


Solution

  • groq query doesnot pick the variable directly from declaration .need to pass the variable in sanityclient.fetch() alongside the query.

    const posts = await sanityClient.fetch(query,{search:search});