andy jones
andy jones

Reputation: 922

Render Props inside of Header Component Next.js React

I have a component inside of my React.js app, using Next.js - this component is the Header I'm using this inside of my layout to get every header element.

What I want to do is get an API request inside of this, so i can render the Menu items inside of the header.. the API is returning the Menu object.

And here is my code.

import fetch from 'isomorphic-unfetch'
import React, { Component } from "react";
import Link from 'next/link';
import { Config } from "../config.js";

class Header extends Component {

    static async getInitialProps() {
        const menuRes = await fetch(
            `${Config.apiUrl}/wp-json/menus/v1/menus/header-menu`   
        );
        const menu = await postsRes.json();
        return {menu}
    }

    render() {
        console.log(this.props);
        return (
            <div>
                213
            </div>
        );
    }
}

export default Header

Im still learning react so please excuse me if I'm 100% wrong on this. Just the Props doesn't return anything for:

this.props

I've not been able to find anyone talking about this online, otherwise I'd happily read a tut on it. Obviously this works on a page.js and returns all my items.

static async getInitialProps(context) {
        const { id } = context.query
        const postsRes = await fetch(
            `${Config.apiUrl}/wp-json/wp/v2/pages?slug=sample-page`   
        );
        const posts = await postsRes.json();
        return {posts}
    }

But I don't know why it wont work inside of the component :(

Upvotes: 2

Views: 1269

Answers (3)

andy jones
andy jones

Reputation: 922

The two answers above are great!! And really helped. Here is the code i used:

constructor() {
        super();
        this.state = { data: [] };
    }

    componentDidMount() {
        fetch(`${Config.apiUrl}/wp-json/menus/v1/menus/header-menu`)
          .then(res => res.json())
          .then(json => this.setState({ data: json }));
    }

Just incase anyone in the future comes across this :)

Upvotes: 1

Werner Potgieter
Werner Potgieter

Reputation: 115

I would recommend fetching your data in componentWillMount and then use your component state to manage this.

create a constructor at the top of your component set the default values and the moment you retrieve the data then setState and render it.

Props are something you send through to a component and state is something you use to manage the data inside your component.

Upvotes: 1

Fabian Hinsenkamp
Fabian Hinsenkamp

Reputation: 302

I would suggest you simply fetch your data in componentDidMount as part of the regular lifecycle of the component. Here you find a great diagram explaining the react lifecycle

Upvotes: 2

Related Questions