0

I am trying to fetch data server side first time if a page is reloaded. For this, I am using getInitialProps in page to get the data. Here is the code that I am trying

    Student.getInitialProps = async (ctx) => {
  
    try {
      const response = await axios({
        method: "get",
        url: `http://localhost:3333/teacher/student/getAllStudent`,
        headers: ctx?.req?.headers?.cookie ? { cookie: ctx.req.headers.cookie } : undefined,
        withCredentials: true,
      })
      console.log("my reso",response.data)
      return { data: response.data }
    } catch (error) {
      if (ctx.res) {
        console.log(error.message)
        ctx.res.writeHead(302, {
          Location: "/",
        })
        ctx.res.end()
      }
    }
  }

this code works perfectly, but I would like to use a function to avoid writing same code/config again and again. Here headers, full url etc all are repeating every pages. How can I write it somewhere and use it from all pages?

Thank you.

1 Answer 1

1

Just make a separate function

For example, your func ./lib/functions/fetchDataFromServer.js

const fetchDataFromServer = async (ctx) => {
    try {
        const response = await axios({
            method: "get",
            url: `http://localhost:3333/teacher/student/getAllStudent`,
            headers: ctx?.req?.headers?.cookie ? {
                cookie: ctx.req.headers.cookie
            } : undefined,
            withCredentials: true,
        })
        console.log("my reso", response.data)
        return {
            data: response.data
        }
    } catch (error) {
        if (ctx.res) {
            console.log(error.message)
            ctx.res.writeHead(302, {
                Location: "/",
            })
            ctx.res.end()
        }
    }
}

export default fetchDataFromServer

and your file at pages directory

import fetchDataFromServer from './lib/functions/fetchDataFromServer'

export async function getInitialProps(ctx) {
    return fetchDataFromServer(ctx)
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would like to keep this file somewhere and use that from all pages, where should I place this js file for fetchDataFromServer function?
@HkmSadek where you want. Edited the answer for an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.