Get data from slug trong nextjs
Để lấy dữ liệu từ params trên url ta có thể code như sau
để tạo 1 slug ví dụ như domain/post/123
Ta tạo trang page.tsx theo đường dẫn folder như sau
\src\app\post\[slug]\page.tsx
Code đọc data như sau
'use client';
import { useRouter } from 'next/navigation';
import React, {useEffect, useState} from "react";
import axios from "axios";
import {fetch} from "next/dist/compiled/@edge-runtime/primitives";
type Params ={
params:{
slug:string;
}
}
//const Post = ({ params:{slug}}:Params) => {
const Post = ({ params:{slug}}:Params) => {
console.log(slug);
console.log(process.env.URL_BASE);
const [data, setData] = useState([]);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
setLoading(false);
let config = {
method: 'get',
maxBodyLength: Infinity,
url: 'https://api.xxxx.com/api/tinh',
headers: {
'token': '123456'
}
};
axios.request(config)
.then((response) => {
//console.log(JSON.stringify(response.data));
setData(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
if (isLoading) return <p>Loading...</p>
if (!data) return <p>No profile data</p>
return (
<>
<h4>{slug}</h4>
{data && data.map((item, index) => (
<h3 key={index}>{item['name']}</h3>
))}
</>
);
}
export async function getServerSideProps() {
return {
props:{
slug,
}
}
}
export default Post;