Dynamic route undefined

58 Views Asked by At

I am using nextjs as the front end of an ecommerce and shopify as the back end. They comunicate through Storefront API.

In the products details page, I have a pay button, which is a client component. When clicked, this button will query shopify and get back the webUrl of the checkout page. But I get an error like this:

index.js:50 POST http://localhost:3000/product/undefined 405 (Method Not Allowed) Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON {status: 500, error: 'Error receiving data'}

My first guess was: the problem is with the dynamic route, becouse I'm getting /product/undefined

But I don't know if that really is the reason, and if it is indeed, don't know how to fix it.

I appraciate if anybody can help!

Thanks!!

Here"s some code:

product/[id]/page.jsx

// 'use client'

// import { useState } from 'react'
import { StarIcon } from '@heroicons/react/20/solid'
import { shopifyFetch } from '../../../utils/index'
import RelatedProducts from '../../components/relatedProducts'
import SubmitFrom from '../../components/payButton'


export async function generateStaticParams() {
  const items = await shopifyFetch(`
    {
      products(first: 3) {
        edges {
          node {
            id
          }
        }
      }
    }
  `)

  // console.log('DATA FROM DYNAMIC: ', items)

  const products = await items.products.edges
  // console.log('PRODUCTS: ', products)

  return products.map((product) => ({
    id: product.node.id
  }))
}

export default async function Example({ params }) {

  const singleProductQuery = `
  query {
    product(id: "gid://shopify/Product/${params.id}") {
      title
      handle
      description
      updatedAt
      tags
      priceRange {
        minVariantPrice {
          amount
        }
      }
      images(first: 1) {
        edges {
          node {
            transformedSrc
            altText
          }
        }
      }
      variants(first: 1) {
        edges {
          node {
            id
          }
        }
      }
    }
    products(first: 3) {
      edges {
        node {
          id
          title
          handle
          tags
          priceRange {
            minVariantPrice {
              amount
            }
          }
          images(first: 3) {
            edges {
              node {
                transformedSrc
                altText
              }
            }
          }
        }
      }
    }
  }
  `

  const item = await shopifyFetch(singleProductQuery)
  const product = item.product
  const variantid = product.variants.edges[0].node.id
  const relatedItems = item.products.edges.filter((item) => item.node.handle !== product.handle).slice(0,4)
  const image = product.images.edges[0].node.transformedSrc
  const imageAltText = product.images.edges[0].node.altText
  // console.log('ITEMS: ', product.variants.edges)
  console.log('PARAMS: ', params.id)

  return (
    <div className="bg-white relative isolate px-6 pt-14 lg:px-8">
      <div className="pt-6">

        <div className="mx-auto mt-6 max-w-2xl sm:px-6 lg:flex lg:max-w-7xl lg:gap-x-8 lg:px-8">

          <div className="hidden lg:grid lg:grid-cols-1 lg:gap-y-8 w-[550px]">
            <div className="aspect-h-5 aspect-w-4 lg:aspect-h-4 lg:aspect-w-3 sm:overflow-hidden sm:rounded-lg">
              <img
                src={image}
                alt={imageAltText}
                className="h-full w-full object-cover object-center"
              />
            </div>
          </div>

          {/* Options */}
          <div className="mt-4 lg:row-span-3 lg:mt-0">
            <h2 className="sr-only">Product information</h2>
            <p className="text-3xl tracking-tight text-gray-900">{product.price}</p>

            {/* payButton */}
            <SubmitFrom variantid={variantid}/>

          </div>
        </div>

        <RelatedProducts products={relatedItems}/>
      </div>
    </div>
  )
}

payButton.jsx


'use client'

import { shopifyFetch } from '../../utils/index'

async function checkout(checkoutMutation) {

    const data = await shopifyFetch(checkoutMutation)
    console.log('SUBMIT FORM COMP TESTING QUERY: ', data)
    // const webUrl = data.checkoutCreate.checkout
    // window.location.href = webUrl
    // window.location.href = 'https://testing-storefront-api-2.myshopify.com/55497818170/checkouts/c6395a3298e5f67e4d649c0e072ad146?key=1b54b10687a6eb8f5b353a535b4b16a6'
  }

export default function PayButton(variantid) {
  console.log('VARIANT ID: ', variantid)
  const variantIdNumber = variantid.variantid.match(/\d+/g)[0]
  console.log('VARIANT ID NUMBER: ', variantIdNumber)

  const checkoutMutation = `mutation {
      checkoutCreate(input: {
        lineItems: {
          variantId: "gid://shopify/ProductVariant/${variantIdNumber}",
          quantity: 1
        }
      }) {
        checkout {
           id
           webUrl
           lineItems(first: 5) {
             edges {
               node {
                 title
                 quantity
               }
             }
           }
        }
      }
    }
    `

  return (
    <div className="mt-10">
      <button
        type="button"
        onClick={() => checkout(checkoutMutation)}
        className="mt-10 flex w-full items-center justify-center rounded-md border border-transparent bg-indigo-600 px-8 py-3 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
      >
        Pay
      </button>
    </div>
  )
}

I tried to call shopifyFetch() with different queries to be sure the problem was not with the queries. The query seems ok. The problem seems to be in generateStaticParams or something related to the dynamic routing...

0

There are 0 best solutions below