Next.js Discord

Discord Forum

404 Error for dynamic route

Answered
Shine posted this in #help-forum
Open in Discord
Hello there, i have some issues with dynamic route, the thing is that i have a directory named "app" and in this directory i got another one named "products". In this one, i have an index.js where it the file for the whole products. I mean look :
Answered by Sun bear
Récupère l'identifiant via les paramètres de la fonction, il me semble que ça fonctionne de la même manière que les slugs
View full answer

25 Replies

"use client";

import { useEffect, useState } from 'react';
import Link from 'next/link';
import styles from '../styles/caroussel.module.css';

export default function Caroussel() {

    const [produits, setProduits] = useState([]);

    useEffect(() => {
        const fetchProduits = async () => {
            try {
                const response = await fetch('http://localhost:8080/produits');
                if (!response.ok) {
                    throw new Error('Erreur lors de la récupération des produits');
                }
                const data = await response.json();
                setProduits(data);
            } catch (error) {
                console.error('Erreur lors de la récupération des produits :', error);
            }
        };

        fetchProduits();
    }, []);

    return (
        <section id={styles.caroussel}>
            <h2>Nos Produits</h2>
            <div className={styles.carousselContainer}>
                {produits.map((produit) => (
                    <div key={produit.id} className={styles.productItem}>
                        <Link href={`/produits/${produit.id}`}>
                            <img
                                src={produit.image}
                                alt={produit.nom}
                                className={styles.productImage}
                            />
                            <div className={styles.productInfo}>
                                <h3>{produit.nom}</h3>
                                <p>{produit.description}</p>
                                <p>{produit.price}€</p>
                            </div>
                        </Link>
                    </div>
                ))}
            </div>
        </section>
    );
}
There is the component where i try to access my dynamic route, and the there is the files for the dynamic route :

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export default function ProduitDetail() {
    const router = useRouter();
    const { produit } = router.query;
    const [produitData, setProduitData] = useState(null);

    useEffect(() => {
        if (categorie && produit) {
            const fetchProduit = async () => {
                try {
                    const response = await fetch(`http://localhost:8080/produits/${produit}`);
                    if (!response.ok) {
                        throw new Error('Erreur lors de la récupération du produit');
                    }
                    const data = await response.json();
                    setProduitData(data);
                } catch (error) {
                    console.error('Erreur lors de la récupération du produit :', error);
                }
            };

            fetchProduit();
        }
    }, [categorie, produit]);

    if (!produitData) {
        return <p>Chargement du produit...</p>;
    }

    return (
        <div>
            <h1>{produitData.nom}</h1>
            <img src={produitData.image} alt={produitData.nom} />
            <p>{produitData.description}</p>
            <p>{produitData.price}€</p>
            <p>Catégorie: {categorie}</p>
        </div>
    );
}
I'll repeat a bit more clearly, but basically I have an issue with my dynamic routes. I'm trying to display products on my main page, and when I click on one, I want it to open another page with the URL
http://localhost:3001/produits/${id}
. So, I created a "produits" folder inside the "app" folder, and inside this folder, I created an index.js file. When I try to access the dynamic route, I get a 404 error. I've shared the code with you. Thank you! 🙂
Dwarf Hotot
change your file name to page.js
what is version of your nextjs
@Dwarf Hotot change your file name to page.js
still not working
@Shine still not working
Sun bear
Pourquoi avoir nommé ton fichier, index.js?
Next.js impose une structure à suivre
@Sun bear Pourquoi avoir nommé ton fichier, index.js?
J'ai toujours nommé mes fichiers index.js cela fonctionnait très bien pour faire des pages statics, mais j'avoue que pour faire une url dynamique je ne sais pas trop
j'ai fais des tests de mon côté et ça ne marche toujours pas :/
j'ai également essayé "page.js"
enfin bref toujours une 404 je suis un peu perdu là
Sun bear
C'est bien la page du fichier [id].js qui n'est pas affichée?
Oui c'est bien celle-là
@Shine Oui c'est bien celle-là
Sun bear
Essaye plutôt de créer un dossier [id] dans ton dossier produits et puis un fichier page.js dans ton dossier [id]
Le fichier page.js doit contenir le code que tu as écrit dans ton fichier [id].js
ça m'a l'air de fonctionner, juste une petite erreur pour récupérer l'id maintenant
Mais tu m'as aidé à résoudre le plus "gros" soucis 🙂 merci beaucoup !
@Shine ça m'a l'air de fonctionner, juste une petite erreur pour récupérer l'id maintenant
Sun bear
Récupère l'identifiant via les paramètres de la fonction, il me semble que ça fonctionne de la même manière que les slugs
Answer
Merci encore pour ton aide 😌