#How to access a parameter when navigating to a Dynamic Route?

1 messages · Page 1 of 1 (latest)

remote holly
#

NextJS 13 and App-directory.

I navigate to a dynamic route using
const onItemClick = (ship: ShipDataProps) => {
router.push(/ship/${ship.imo});
};

I want to bring ship.imo with me and fetch data based on the dynamic route number.

export default async function Page({ params }: { params: { ship: number } }) {
const [data, setData] = useState<NsrDataProps>();

What do I need to fix?

minor orbitBOT
#

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

#

To fetch data based on the dynamic route number, you can use a Client Component with useSWR for data fetching. Here's an example of how you can modify your code:

  1. First, import useSWR:
import useSWR from 'swr';
  1. Create a fetcher function:
const fetcher = (url: string) => fetch(url).then((r) => r.json());
  1. Use useSWR to fetch data based on the ship.imo:
export default function Page({ params }: { params: { ship: number } }) {
  const { data, error } = useSWR(
    `https://your-api-url/ship/${params.ship}`,
    fetcher,
  );

  if (error) return 'Failed to load';
  if (!data) return 'Loading...';

  // Render your component with the fetched data
  return <YourComponent data={data} />;
}

Replace https://your-api-url/ship/ with the actual API URL you want to fetch data from.

This example is based on the information extracted from the Next.js Beta documentation on Static Export (https://beta.nextjs.org/docs/configuring/static-export).

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

#

@remote holly kapa.ai is still learning and improving, please let us how it did by reacting below

remote holly
#

@minor orbit export default async function Page({ params }: { params: { ship: number } }) {
const [shipData, setShipData] = useState<NsrDataProps>();

useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.post<NsrDataProps>("/api/ship/", { imo: params.ship });
console.log(data)
setShipData(data);
} catch (error) {
console.log(error);
}
}
fetchData();
}, []);

console.log(shipData)
console.log(params.ship)

shipData always ends up empty.

minor orbitBOT
#

Let me check the knowledge base for you. One moment! :books:

#

It seems like you're using axios to fetch data and useState with useEffect to manage the fetched data. The issue might be related to the dependency array in useEffect. You should add params.ship to the dependency array to ensure the effect runs when the ship value changes.

Here's the updated code:

import { useState, useEffect } from 'react';
import axios from 'axios';

export default function Page({ params }: { params: { ship: number } }) {
  const [shipData, setShipData] = useState<NsrDataProps>();

  useEffect(() => {
    async function fetchData() {
      try {
        const { data } = await axios.post<NsrDataProps>("/api/ship/", { imo: params.ship });
        console.log(data);
        setShipData(data);
      } catch (error) {
        console.log(error);
      }
    }
    fetchData();
  }, [params.ship]); // Add params.ship to the dependency array

  console.log(shipData);
  console.log(params.ship);

  // Render your component with the fetched data
}

By adding params.ship to the dependency array, the useEffect will re-run whenever the ship value changes, ensuring that the data is fetched and updated correctly.

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

#

@remote holly kapa.ai is still learning and improving, please let us how it did by reacting below

remote holly
#

@minor orbit I did that, but shipData is still empty. How do I properly fetch data using a POST-request in a "use client" component in NextJS 13? I want to use the params that comes along with the routing.

minor orbitBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To fetch data using a POST request in a "use client" component in Next.js 13, you can use the useEffect hook along with axios. Here's an example of how you can modify your code:

  1. First, add the 'use client' directive at the top of your file:
'use client';
  1. Import the necessary dependencies:
import { useState, useEffect } from 'react';
import axios from 'axios';
  1. Use useState and useEffect to fetch data based on the params.ship:
export default function Page({ params }: { params: { ship: number } }) {
  const [shipData, setShipData] = useState<NsrDataProps>();

  useEffect(() => {
    async function fetchData() {
      try {
        const { data } = await axios.post<NsrDataProps>("/api/ship/", { imo: params.ship });
        console.log(data);
        setShipData(data);
      } catch (error) {
        console.log(error);
      }
    }
    fetchData();
  }, [params.ship]);

  console.log(shipData);
  console.log(params.ship);

  // Render your component with the fetched data
}

Make sure your API endpoint /api/ship/ is set up correctly to handle POST requests and return the expected data. If the issue persists, it might be related to the API endpoint or the data format.

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