简体   繁体   中英

How to fetch the API details from a component folder using Next.js?

I have a reusable component that I have created on the components folder where I have all the details from the user that logs in to the system which is a header section.

I am trying to use getInitialProps using fetch with isomorphic-unfetch .

static async getInitialProps(ctx) {
    const UserdetailsRespone = await fetch("my API url");
    const UserdetailsJson = await UserdetailsRespone.json();
    return { UserDetails: UserdetailsJson.root[0] };
 }

In the render method when I log this.props.UserDetails I get undefined . It is the same API fetch as the one I am doing in the pages folder where I am able to fetch an API response. But I am not able to fetch the response in the components folder.

Can someone help me to solve it? Thanks in Advance.

If you're using getInitialProps in a child component, it won't work. It only works in the default export of every page. From official docs

Edit: As mentioned by Uzair Ashraf, using fetch is the way to go for fetching data in components. You can take a look at swr too.

getInitialProps runs server side and client side. So you will have to be careful how you use it. I usually use typeof Window === 'undefined' to check whether getInitialProps is being called server side or not.

If you have a child component that you need to make a call everytime it is mounted, why not stick with componentDidMount ?

async componentDidMount() {
    const userDetailsResponse = await fetch("my API url");
    const userDetailsJson = await userDetailsResponse.json();
    this.setState({userDetails: userDetailsJson})
}

You can access the properties from state instead of props then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM