Search code examples
wordpressreactjsrestapiheadless

Trying to do an api fetch using id from earlier api fetch


So I've tried to find information regarding this and I'm feeling quite stuck. I'm running headless wordpress using react and I have a page who fetch my single post and return it.

Every post (custom post type called Tjanster) has an acf field with a relation to another custom post type which is the Person associated with the post.

Right now everything works with getting the post content as well as the person object with ID and slug etc. But I need the ACF content from that "person post type.

My idea right now is that I acquire the ID from the person object in the post and then do another api-fetch for that id directly towards the person endpoint, is that correct thinking?

This is my post json that I get with the acf.person[0].id from (http://localhost:8080/wp-json/wp/v2/tjanster)

enter image description here

Here I get the ID of the person which is 68 and then I can do a request to http://localhost:8080/wp-json/wp/v2/person/68 which returns the object with the correct acf info:

enter image description here

And this is how my tjanster.js (single-post-page) looks right now:

import Layout from "../components/Layout.js";
import React, { Component } from "react";
import fetch from "isomorphic-unfetch";
import Error from "next/error";
import PageWrapper from "../components/PageWrapper.js";
import Menu from "../components/Menu.js";
import { Config } from "../config.js";

class Tjanster extends Component {
    static async getInitialProps(context) {
        const { slug, apiRoute } = context.query;

        const res = await fetch(
            `${Config.apiUrl}/wp-json/postlight/v1/${apiRoute}?slug=${slug}`
        );
        const tjanster = await res.json();

        return { tjanster };
    }


    render() {
        if (!this.props.tjanster.title) return <Error statusCode={404} />;

        let personId = this.props.tjanster.acf.person[0].ID;
        console.log(personId);

        return (
            <Layout>

                {this.props.tjanster.title.rendered}

            </Layout>
        );
    }
}

export default PageWrapper(Tjanster);

As you can see I have the id of the person object saved under render as personId but I'm not entirely sure what to do next? I figured I could do another fetch at the top using ${Config.apiUrl}/wp-json/wp/v2/person/${personId} but I won't get that to work since I can't access the ID yet.

Any ideas would be greatly appreciated!


Solution

  • You need to use javascript Promise to handle multiple asynchronous calls. Just chain a then after your first fetch, you will be able to access to the Id when it will be available.