Home > Net >  How can I filter slug data
How can I filter slug data

Time:06-20

I'm using sanity to get slug data and I just wan't to show related posts from the same post category.

I tried to fetch all data and pass it to the state. but I have no idea how to get current posts category and filter the data. I think I need to use useRouter but I'm not sure. Thank you for your help!

[slug].tsx


/// MY ATTEMPT

const [data, setData] = useState([] as any [])
  useEffect(() => {
  sanityClient.fetch(`*[ _type == "postschema"] {
        _id,
        title,
        category,
    }`
    ).then(result => {
    setData(result)
  })
}, [])

///

const SingleProject = ({projects} : any) => {
return (
    <>
        <>
          <div className="single__page">
            <div className="down__arrow">
   
            </div>
            <div className="single__header">
              <h2>{projects.category}</h2>

{*HERE I WANT TO SHOW SIMILAR POSTS FROM THE SAME CATEGORY*}
            </div>
          </div>

}

export const getServerSideProps: GetServerSideProps = async ({params}) => {
      const query = `*[_type == "projectschema" && slug.current == $id][0] {
     _id,
        title,
         category,
         date,
         website,
        thumbnail,
         client,
         company,
       description,
       review,
       author,
       authorjob,
       image1,
       image2,
       image3,
       image4,
       image5,
        slug
    }`;


const projects = await sanityClient.fetch(query, {
    id: params?.id,
    
})

  if(!projects) {
    return {
        notFound: true
    }
  }


  return {
    props: {
        projects,
    }
  }
}



CodePudding user response:

something like this?

{
    data.filter(a=>a.category === projects.category)
        .map(r => {
            return (
              <div>
                output info {project.category}
              </div>
            )
        })
}
  • Related