Next.js use Url Parameter to make Api Request and Display result on Page
In a Next.js application, you can use the getInitialProps
lifecycle method to make an API request using a URL parameter and then display the result on the page. The getInitialProps
method is called before the component is rendered on the server or client, and it's where you can fetch any data that the component needs.
Here's an example of how you might use getInitialProps
to make an API request using an ID parameter from the URL:
import { useRouter } from 'next/router';
import axios from 'axios';
function MyPage({ data }) {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>My Page</h1>
<p>The ID is {id}</p>
<p>The data is {data}</p>
</div>
);
}
MyPage.getInitialProps = async ({ query }) => {
const { id } = query;
const res = await axios.get(`https://jsonplaceholder.typicode.com/todos/${id}`);
const data = res.data;
return { data };
};
export default MyPage;
In this example, the getInitialProps
method is making an API request to https://jsonplaceholder.typicode.com/todos/
and passing the id
parameter from the URL query string. The response from the API is stored in a data
variable, which is then passed to the component as a prop. The component then displays the data
and id
on the page.
If this function runs on the server, it will get the initial props and include it in the rendered html. If it runs on client, the data will be passed to the component as props before the component is rendered.
You can also use useEffect
and useState
hooks to make api request and update the state.
import { useRouter } from 'next/router';
import axios from 'axios';
function MyPage() {
const router = useRouter();
const { id } = router.query;
const [data, setData] = useState(null);
useEffect(() => {
async function getData() {
const res = await axios.get(`https://jsonplaceholder.typicode.com/todos/${id}`);
setData(res.data);
}
getData();
}, [id]);
return (
<div>
<h1>My Page</h1>
<p>The ID is {id}</p>
<p>The data is {data}</p>
</div>
);
}
export default MyPage;
This allows you to avoid running the api call on server side and only call it after the component is mounted on the client, while still allowing your component to correctly render on the server.
Keep in mind that, the getInitialProps
method runs on the server for each request, so you should make sure to handle cases where there's no ID or where the API request fails gracefully to avoid server-side errors.