Search code examples
reactjsapiroutesnext.jsvercel

How to use API Route in next js?


I am learning how to design API and at the same time how to use next.js API route.

I have set my first route api/property/[propertyId] that returns the specific property detail.

Now I am trying to set a dynamic route for the specific property id in the page folder page/property/[propertyId]. My issue is when I am getting directed on the specific page the data is not there as expected. I am receiving a response for error message.

Can someone point out what I did wrong, please?

pages>api>property>[propertyId]

export default function propertyHandler ({query : {propertyId} } ,res) {
    var parser = new xml2js.Parser({explicitArray : false});
    const data = fs.readFileSync(path.join(process.cwd(),'listing.xml'))
    parser.parseString(data,function (err, results){
        results = results.client.secondhandListing.property
    
        const filteredProp = results.filter((property) => property.id === propertyId)
        filteredProp.length > 0 ?  res.status(200).json(filteredProp[0]) : res.status(404).json({message: `Property with id: ${propertyId} not found.` })
    })
}

pages>property>[id].js
 
export const getDetails = async() => {
      const res = await fetch(`${baseUrl}/api/property/[property.Id]}`)
      const data = res.json()

      return data
  }

export async function getServerSideProps({params: { id } }) {
    const data = await getDetails(`${baseUrl}/api/property/${id}`)

    return {
        props: {
            propertyDetails: data
        }
    }
}

Solution

  • I got the answer to my mistake from somewhere else. It was my getdetails function that was wrong.

    I have amended it to:

    export const getDetails = async(baseUrl)=>{
        const res = await fetch(baseUrl)
        const data  = await res.json()
        return data
        
    };
    

    and it worked.