How to fetch Menu from wordpress?

Hello @joppe could you provide a public repo or a codesandbox reproducing the error? This way it will be easier for the community to help you.

The code I got working doesn’t assign data but rather pulls items.items to an items property and that works well.

Hello Pablo,

Sorry I cannot provide a public repo or sandbox.

Maybe I can rephrase my question a bit.

The method Object.assign expects two properties. The first one is the target property where the key/values will be copied to. In the example state.source.data["primaryMenu"] is provided. In my case this property is undefined, so the assign won’t work. Should the property be created by the framework? Is there a setting I should add, so it will be generated?

This is the code I use

import * as React from 'react';

import Theme from './Theme';

const menuHandler = {
    name: 'primaryMenu',
    pattern: 'primaryMenu',
    priority: 10,
    func: async ({ libraries, state }): Promise<void> => {
        const response = await libraries.source.api.get({
            endpoint: 'menu/all',
        });

        const items = await response.json();

        Object.assign(state.source.data['primaryMenu'], {
            items,
            isMenu: true,
        });
    },
};

export default {
    name: 'zimpa',
    roots: {
        theme: Theme,
    },
    actions: {
        theme: {
            beforeSSR: async ({ actions }): Promise<void> => {
                await actions.source.fetch('primaryMenu');
            },
        },
    },
    libraries: {
        source: {
            handlers: [menuHandler],
        },
    },
};

Hey @joppe,

I am going to try to answer this, but please someone correct me if I am wrong.
When you use actions.source.fetch('primaryMenu') that will use the primaryMenu handler to fetch a certain endpoint. In your case I can see the endpoint is 'menu/all'.
As far as I understand, when get request is performed, the response is placed in state.source.data[link]. The idea is to then wait for the reposnse to resolve and get the items from it and add them to that object in state.source.data[link].

I believe in your case you need to look at state.source.data['menu/all']. The easiest way to test this is just open the browser console, type frontity.state.source.data and review what you have there. This will help you find the solution.

Good luck and hopefully this was helpful in 1 way or another.

1 Like

I quick suggestion (not sure if it is the solution) in addition to what was explained by @ni.bonev

const menuHandler = {
    name: 'primaryMenu',
    pattern: 'primaryMenu',
    priority: 10,
    func: async ({ link, libraries, state }): Promise<void> => {
        const response = await libraries.source.api.get({
            endpoint: 'menu/all',
        });

        const items = await response.json();

        Object.assign(state.source.data[link], {
            items,
            isMenu: true,
        });
    },
};

What I’m doing here is using the param link from the function, because if I remember correctly, the link will be primaryMenu/. That’s the reason you get undefined, because the link is being modified to always have a / at the end.

2 Likes

Using the link works indeed :tada:
Thanks for explaining @orballo and @ni.bonev!

3 Likes

Hi,
I followed your example and I can call the menus, but I have an issue; I can’t access the resources of these different menus;
Could you please help me?

Hi @eudeskouassi :wave:
In order to get help most efficiently it’s essential that you provide a bit more details about your problem: :slight_smile:

What specific errors are you getting in the terminal?
What specific errors are you getting in the browser’s console?
If you could provide a repository with the code of your project, the community (or any member of the Frontity team) would be able to clone your project and try to reproduce the issue you’re having
With this info, it’ll be much easier to help you with your issue

If you can’t share your whole project, please create a CodeSandbox (you can start with this template) or a GitHub repository with the minimal amount of code to reproduce the issue.

Hi @SantosGuillamot
Pleqse, how to install this plugin https://github.com/WP-API/menus-endpoints ?

You can download the zip from the GitHub repo and upload it to your WordPress as any other plugin -> https://www.wonderplugin.com/wordpress-tutorials/how-to-manually-install-a-wordpress-plugin-zip-file/#:~:text=This%20tutorial%20will%20guide%20you,click%20the%20button%20Install%20Now.

Thank you !
It’s okay

Is it possible to use Console.logs in the index.js files? I followed the instructions here and I have written the code correctly to get the menus using the WP-REST-v2 Menus plugin but I am getting items undefined in the Nav.js component.

The code in my index.js file.


const menuHandler = {

  name: 'menus',

  priority: 10,

  pattern: '/menus/:slug', // You can use something shorter here, you don't need to use the endpoint

  func: async ({ route, params, state, libraries }) => {

    const { api } = libraries.source

    const { slug } = params

    // 1. fetch the data you want from the endpoint page

    const response = await api.get({

      endpoint: `/menus/v1/locations/${slug}` 

    });

    // 2. get an array with each item in json format

    const items = await response.json();

   

    // 3. add data to source

    const currentPageData = state.source.data[route];

    Object.assign(currentPageData, {

      slug,

      items: items.items, // @ni.bonev figured this one out because the "items" property contains "items" that are the menu items we are after

      isMenu: true

    })

  }

}
beforeSSR: async ({ actions }) => {

      // Adding both menu location menus to beforeSSR

      await actions.source.fetch('/menus/primary')

      await actions.source.fetch('/menus/footer-menu')

  }
source: {

      handlers: [menuHandler]

    }

Hi @chinomsojohnson,

Welcome to the Community!

Can you please provide a repo or code-sandbox with your code? This is especially helpful to find solutions of technical issues with specific code

Regarding the use console.log in your code maybe this Frontity Talk we recently published about debugging may help you