#Dynamic Routing with Fetch and UseEffect

1 messages · Page 1 of 1 (latest)

small iron
#

Give me an example on how I can do dynamic routing with fetch and use effect to show data of a product when the botton of that product and then get the product info from the db (drizzle orm and sqlite)

proud templeBOT
#

Hi @small iron. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, I can show you how to use dynamic routing with fetch and useEffect in Next.js, but I don't have specific information about using Drizzle ORM and SQLite.

In Next.js, you can use dynamic routing by creating a file with square brackets in the name, like [id].js in the pages directory. This file will match any route like /product/1, /product/2, etc., and the part of the URL in the brackets will be passed as a parameter to your page.

Here's an example of how you might fetch data for a product in a Next.js page using useEffect:

import { useState, useEffect } from 'react'

function Product({ id }) {
  const [product, setProduct] = useState(null)
  const [isLoading, setLoading] = useState(true)

  useEffect(() => {
    fetch(`/api/product/${id}`)
      .then((res) => res.json())
      .then((data) => {
        setProduct(data)
        setLoading(false)
      })
  }, [id])

  if (isLoading) return <p>Loading...</p>
  if (!product) return <p>No product data</p>

  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
    </div>
  )
}

In this example, useEffect is used to fetch the product data from the server whenever the id prop changes. The id prop would be provided by Next.js based on the URL of the page.

Please note that this is a simplified example and doesn't include error handling. Also, the URL /api/product/${id} in the fetch call is just an example, and you would need to replace it with the actual URL of your API.

For more information, you can refer to the Next.js documentation on Dynamic Routing (https://nextjs.org/docs/routing/dynamic-routes) and Data Fetching (https://nextjs.org/docs/basic-features/data-fetching).

#

For using Drizzle ORM and SQLite, you might need to refer to their respective documentation or other resources, as the knowledge sources provided don't include information on these topics.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: