Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get the id url from next js and use it with axios

I’ve been trying to make a get request with axios, but it doesn’t work because the id const doesn’t load and is marked as undefined. Here is my code:

import Head from 'next/head'
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/router'


export default function QuejaID() {
    const router = useRouter()
    const id = router.query.id
    console.log(id)
    const [queja, setQueja] = useState();

    useEffect(() => {
        async function request() {
            await axios.get(
                `http://localhost:3000/quejas/${id}`
            ).then((response) => {
                setQueja(response.data)
                console.log(response)
            }).catch(err => { console.log(err) })
        }
        request()
    }, []);

    return (
        <>
            <Head>
                <title>Quejas</title>
                <meta name="description" content="queja" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <main>
                {queja ? <div className="container d-flex justify-content-center">
                    <div className="card text-center w-75 m-5">
                        <div className="card-header">{queja._id}</div>
                        <div className="card-body">
                            <h5 className="card-title">{queja.queja}</h5>
                        </div>
                        <div className="card-footer text-muted">{queja.createdAt}</div>
                    </div>
                </div> : <div>No hay ninguna queja con ese ID</div>}
            </main>
        </>
    )
}

So I tried with that and I get an error with axios because it’s undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

add id to the dependency array

useEffect(() => {
        async function request() {
            await axios.get(
                `http://localhost:3000/quejas/${id}`
            ).then((response) => {
                setQueja(response.data)
                console.log(response)
            }).catch(err => { console.log(err) })
        }
        request()
    }, [id]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading