Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  78] [ 6]  / answers: 1 / hits: 28428  / 3 Years ago, sat, september 4, 2021, 12:00:00

I want to query my Supabase table using the ID in the slug e.g. localhost:3000/book/1 then show information about that book on the page in Next.js.


Table


enter


book/[id].js


import { useRouter } from 'next/router'
import { getBook } from '@/utils/supabase-client';

export default function Book({bookJson}) {
const router = useRouter()
const { id } = router.query

return <div>
<p>Book: {id}</p>
<h1>{bookJson}</h1>
</div>
}

export async function getServerSideProps(query) {
const id = 1 // Get ID from slug
const book = await getBook(id);
const bookJson = JSON.stringify(book)

return {
props: {
bookJson
}
};
}

utils/supabase-client.js


export const getBook = async (id) => {
const bookString = id
let bookId = parseInt(bookString);

const { data, error } = await supabase
.from('books')
.select('id, name')
.eq('id', bookId)

if (error) {
console.log(error.message);
throw error;
}

return data || [];
};

More From » next.js

 Answers
52

You can access the route parameters through getServerSideProps's context, using the params field.



params: If this page uses a dynamic route, params contains the route parameters. If the page name is [id].js, then params will look like { id: ... }.


Next.js, Data Fetching: getServerSideProps, Context parameter



export async function getServerSideProps(context) {
const id = context.params.id // Get ID from slug `/book/1`

// Rest of `getServerSideProps` code
}



Alternatively, you can also use the query field to access the route parameters. The difference is that query will also contain any query parameter passed in the URL.


export async function getServerSideProps(context) {
const id = context.query.id // Get ID from slug `/book/1`
// If routing to `/book/1?name=some-book`
console.log(context.query) // Outputs: `{ id: '1', name: 'some-book' }`

// ...
}

[#50191] Saturday, August 7, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;