V
V
Vladimir2020-11-10 07:22:23
React
Vladimir, 2020-11-10 07:22:23

During the initial rendering, the router returns undefined, what should I do?

Good morning. Can you please tell me how to pass the value after final rendering?

import Head from 'next/head';
import TopBar from "../../components/lowLvlComponents/topBar/topbar";
import GetCompanyPage from "../../components/companyPage/company";
import Footer from "../../components/footer/footer";
import {useRouter} from "next/router";

import {url} from "../../serverConfig";

export default function Home() {

    const router = useRouter()
    const id = router.query.id;

    // if(!id) return null; // Если юзать это, то undefined скипается, однако с ним и запрос на сервер почему-то.

    const getCompany = async() => {

        const data = await fetch(`${url}/selectCompany`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: id
            })
        });

        return await data.json()

    };

    console.log(id);

    getCompany().then(el => console.log(el));

    return (
        <div className="container">

            <Head>
                <title>Company</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <TopBar />
            <GetCompanyPage company={company} />
            <Footer />

        </div>
    )
}


On initial rendering, undefined, followed by a value.

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twolegs, 2020-11-10
@twolegs

You get the value asynchronously.
1. To update the component after receiving data, you need to use the state.
2. For side effects, you need to use useEffect.

export default function Home() {

    const router = useRouter()
    const id = router.query.id;

    const [company, setCompany] = useState(null);

    useEffect(() => {
        fetch(`${url}/selectCompany`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: id
            })
        })
        .then(response => response.json())
        .then(result => setCompany(result));
    }, [id, setCompany])

    return company ? (
        <div className="container">

            <Head>
                <title>Company</title>
                <link rel="icon" href="/favicon.ico" />
            </Head>

            <TopBar />
            <GetCompanyPage company={company} />
            <Footer />

        </div>
    ) : null;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question