#Nextjs 13 dynamic routes + Strapi "fetch failed"

4 messages · Page 1 of 1 (latest)

red bridge
#

hi,

You can imagine getServerSideProps as backend and you shouldn't fetch data from backend to backend right?

You can directly write your api to inside getServerSideProps or fetch your api inside your component

empty dust
#

Alright, but don't know how... is there a documentation for this?

red bridge
#

basically you can copy paste your api/contents/i-am-a-post code into getServerSideProps

For more info:
https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

example code:

export async function getServerSideProps(context: any) {
    let quizzId = context.query.quizzId;
    let questionId = context.query.question;

    if (quizzId && questionId) {
        const connection = await mysql.createConnection(
            String(process.env.DATABASE_URL)
        );

        try {
            const [questions] = await connection.query(
                `SELECT id, question, correctAnswer, answer
                FROM Questions
                WHERE id = ? quizzId = ?`,
                [questionId, quizzId]
            );
            const [count] = await connection
                .query(
                    `SELECT COUNT(question) FROM QuizzApp_Questions AS questionCount WHERE quizzId = ?`,
                    [quizzId]
                );
            if (!questions) {
                return { props: { data: "Error" } };
            }
            return { props: { data: { questions, count } } };
        } catch (error) {
            console.error(error);
            return { props: { data: error } };
        } finally {
            await connection.end();
        }
    } else {
        console.log("No match found");
        return { props: { data: "Error" } };
    }

Fetch data on each request with getServerSideProps.