Home > Enterprise >  NextJs - load dynamic data to the main page from different file
NextJs - load dynamic data to the main page from different file

Time:07-15

I am trying to add dynamic data from one file to another and am having issues with that.

The data I am trying to load from

path: /src/components/Subnav.js

import React, { Component } from "react";
class Subnav extends Component {
    static async getInitialProps(ctx) {
        const res = await fetch("https://api.github.com/repos/vercel/next.js");
        const json = await res.json();
        return { stars: json.stargazers_count };
    }
    render() {
        return <div>Next stars: {this.props.stars}</div>;
    }
}

export default Subnav;

The code where I want the above data in

import React from "react";
import Subnav from "../src/components/Subnav";
function Page({ json }) {
    return (
        <subNav />
    )
}

output in the browser

<div>Next stars: </div>

The expected output in the browser

<div>Next stars: 88542</div>

Issue: As you can see above, I am just seeing the static text which is "Next stars" however, i am not seeing the data from the JSON

CodePudding user response:

getInitialProps is data fetching method for page, it means you only can use it inside /pages folder. If you want fetching data for components, you can use useEffect.

import React, { useEffect, useState } from "react";

const Subnav = () => {
    const [stars, setStars] = useState(null);
    useEffect(() => {
        const getStars = async () => {
            const res = await fetch("https://api.github.com/repos/vercel/next.js");
            const json = await res.json();
            setStars(json.stargazers_count)
        }
        getStars();
    }, [])

    return <div>Next stars: {stars}</div>
}

export default Subnav;
  • Related