The React admin ReferenceInput Component is not functioning properly when utilized with a hydra response

It seems like I might have missed something, as I am unable to find the reason why all my results are loaded for the station field but no autocomplete suggestions are being displayed under the field.

I also attempted using a SelectInput component, but the list of options is empty.

The custom query in Redux was successful:

My code for the create and edit sections is quite similar:

import React, {FC} from "react";
import {
    CreateGuesser,
    InputGuesser
} from "@api-platform/admin";
import {ReferenceInput, AutocompleteInput, FilterProps} from "react-admin";

const RefuelsCreate : FC<Omit<FilterProps, 'children'>> = props => (
    <CreateGuesser {...props}>
        <InputGuesser source="pricePerLiter" />
        <ReferenceInput
            source="stationId"
            reference="gaz_stations"
            label="Station"
            filterToQuery={searchText => ({ address: searchText })}
        >
            <AutocompleteInput optionText="address" />
        </ReferenceInput>
        <InputGuesser source="totalRefuelPrice" />
        <InputGuesser source="kmTravelled" />
    </CreateGuesser>
);

export default RefuelsCreate;

Both the Edit and Create sections are not functioning properly for this ReferenceInput.

In my App.tsx file, I included this component within a ResourceGuesser component.

import React from "react";
import { Redirect, Route } from "react-router-dom";
import { HydraAdmin, ResourceGuesser, hydraDataProvider as baseHydraDataProvider, fetchHydra as baseFetchHydra, useIntrospection } from "@api-platform/admin";
import parseHydraDocumentation from "@api-platform/api-doc-parser/lib/hydra/parseHydraDocumentation";
import authProvider from "./Auth/AuthProvider";
import { Layout } from './layout'
import customRoutes from './routes';
import themeReducer from './themeReducer';
import polyglotI18nProvider from 'ra-i18n-polyglot';
import englishMessages from './i18n/en';
import { Dashboard } from './dashboard';
import refuels from './refuels';

const i18nProvider = polyglotI18nProvider(locale => {
    if (locale === 'fr') {
        return import('./i18n/fr').then(messages => messages.default);
    }

    // Always fallback on english
    return englishMessages;
}, 'en');


const entrypoint = `${process.env.REACT_APP_API_URL}`;
const getHeaders = () => localStorage.getItem("token") ? {
    Authorization: `Bearer ${localStorage.getItem("token")}`,
} : {};

const fetchHydra= ((url: any, options = {}) =>
    baseFetchHydra(url, {
        ...options,
        headers: getHeaders,
    })
);

const RedirectToLogin = () => {
    const introspect = useIntrospection();

    if (localStorage.getItem("token")) {
        introspect();
        return <></>;
    }
    return <Redirect to="/login" />;
};

const apiDocumentationParser = async (entrypoint:any) => {
    try {
        const { api } = await parseHydraDocumentation(
                entrypoint,
                {
                    // @ts-ignore
                    headers: getHeaders
                }
            );
        return { api };
    } catch (result) {
        if (result.status === 401) {
            // Prevent infinite loop if the token is expired
            localStorage.removeItem("token");

            return {
                api: result.api,
                customRoutes: [
                    <Route path="/" component={RedirectToLogin} />
                ],
            };
        }

        throw result;
    }
};

const dataProvider = baseHydraDataProvider(entrypoint, fetchHydra, apiDocumentationParser, true);

export default () => (
    <HydraAdmin
        title="ease daily app"
        customReducers={{ theme: themeReducer }}
        dataProvider={ dataProvider }
        authProvider={ authProvider }
        entrypoint={ entrypoint }
        layout={Layout}
        dashboard={ Dashboard }
        customRoutes={customRoutes}
        i18nProvider={i18nProvider}
    >
        <ResourceGuesser name="refuels" list={refuels.list} create={refuels.create} edit={refuels.edit}/>
    </HydraAdmin>
);

As per the documentation at , it seems that I am following the correct process and everything should work. However, I am puzzled as to why no suggestions are being displayed.

Answer №1

When incorporating a reference to another resource, it is essential to add it as a resource following the guidelines provided in the documentation: https://i.sstatic.net/LcZuM.png

Extracted from this source

To achieve this in your code, simply insert the following line into your App.tsx file:

        <ResourceGuesser name="gaz_stations"/>

Subsequently, the referenced field will be sourced from the API

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Successive type label

Looking to create an object that can have either primitives or objects as properties? Avoid pitfalls like the following: const obj: DesiredType = { correctProp1: 'string', correctProp2: 123, correctProp3: true, wrongProp4: [1, 2, 3], pr ...

Error: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

MUI is designed to only manage either onBlur or onKeyPress, but not both simultaneously

Currently, I am working on a project with TypeScript and Material-UI. My main goal is to handle both the onBlur event and the onEnter key press event for a TextField component. Here's the scenario: I have incorporated this text field into a menu. Whe ...

Encountered an error stating "Cannot find module node:fs" while using eslint-typescript-import, eslint-import-resolver-typescript,

Challenge My attempt to configure path alias in my TypeScript project was met with failure. Two errors arose during the execution of npm start: Module not found: Error: Can't resolve '~/App' in 'D:\work\workbench\templa ...

Utilizing an array of data to create a complex structure with nested

In my Next.JS React project using TSX files, I have set up a data file like this: const fieldMapping = { category:[ { title: "Category 1", Subtitle: ["Category 1", "Category 2"], SubSubTitle: ["Category ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

Encountering crashes while initializing the router in the constructor of a service in Angular 4.3

I've been scratching my head over this problem. It seems like I'm overlooking something simple. Let me show you what's inside my home.component.ts file: import { Component, OnInit } from '@angular/core'; import { AuthService } f ...

Ways to immediately display an uploaded image as the background on a canvas

Using TypeScript, I am attempting to set an uploaded image as the background of a canvas. However, I am facing an issue where the image only loads properly after the user has uploaded it two times. How can I ensure that the image has finished loading befor ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

React's useState hook is failing to update the value

In my React TypeScript project, I am facing an issue with updating the value using useState. I have initialized the state with const [isGameStarted, setIsGameStarted] = React.useState<any>('0');, and then updated it in the useEffect() funct ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use. ngOnInit(): void { this.http.get<APIResponse>('ur ...

Tips for establishing secure communication between a shell app and micro application (frontend) using pubsub technology

I have developed a shell application that serves as the main container for handling all API communications. Additionally, I have created several Micro applications that simply send API request signals to the shell application. When it comes to security, m ...

Managing Angular routing: selectively updating named outlets without reloading submodules

My routing configuration currently reloads Module2 ListComponent on every routing event. However, I want to prevent the list from reloading when a user clicks on a list item within ListComponent. Specifically, when navigating from module2/route1 to module ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

The 'src' properties in nextjs/image are of different types and therefore cannot be used interchangeably

I'm currently using React Dropzone to upload multiple images in my basic application. To display the types of images that are being dropped, I created a separate component with TypeScript. However, Next.js is throwing an error when it comes to the ima ...

Unlock the potential of ng-for to dynamically generate input boxes and checkboxes!

In this Angular application, my requirement is to repeat the elements inside a div based on the number entered in an input box (record.accountRoles). <!-- Input Box --> <div class="form-group"> <label for="name">Enter the number of a ...

Make sure to always verify the condition every time

Below is the code I'm using to render multiple instances: I have two sections, one with the 'show-all' class and the other with no class. If the 'show-all' class is not present, the countIncrease function needs to be executed. If ...

Error: Null is causing an issue and preventing property 'isSkipSelf' from being read in Angular7

While assembling the package for my module, I encountered the following error. TypeError: Cannot read property 'isSkipSelf' of null at ProviderElementContext._getDependency(C:\Users\ravinder\MyProjectName\node_modules\@ ...

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...