Error encountered while processing Graphql response: The string is unable to accurately represent the value of

I'm encountering an issue with GraphQL while attempting to retrieve the name of an airport from JSON data. Instead of receiving a single item containing just the airport name, I'm getting an array with additional details like city, country, geolocation, and more. Below is the code I am using...

const getNameOfAirport = (name:any)=>{
    return AIRPORTS.filter((i)=>{
        if(i.iata_code === name){
            return i.name.length;
        }
    })
}

When running console.log(getNameOfAirport("BLR")), the output includes:

[
  {
    name: 'Bangalore',
    city: 'Bangalore',
    country: 'India',
    iata_code: 'BLR',
    _geoloc: { lat: 12.949986, lng: 77.668206 },
    links_count: 195,
    objectID: '3131'
  }
]

My desired response is simply "Bangalore". Any assistance on this matter would be greatly appreciated. Please advise me on where I may have made an error.

Additional Note: I am utilizing TypeScript. It functions correctly with JSX as anticipated, but seems to be behaving incorrectly with TS.

Answer №1

There are a few mistakes that need to be addressed:

While you are using Typescript, it seems unnecessary to use any as your type. This defeats the purpose of using Typescript in the first place.

const getNameOfAirport = (name:any)=>{
    return AIRPORTS.filter((i)=>{
        if(i.iata_code === name){
            return i.name.length;
        }
    })
}

The function references the array AIRPORTS but does not receive it as an argument. It's best practice to avoid side effects by passing all necessary data into the function.

You should consider using .find() instead of Array.filter() for this use case.

It's recommended to create an interface like this:

const getNameOfAirport = (
  airports: Airport[],
  name: string
): string | undefined => {
  return airports.find((airport) => airport.iata_code === name)?.name;
};

interface Airport {
  name: string;
  city: string;
  country: string;
  iata_code: string;
  _geoloc: {
    lat: number;
    lng: number;
  };
  links_count: number;
  objectID: string;
}

To call the function, use:

getNameOfAirport(AIRPORTS, "BLR")

As a suggestion, consider renaming getNameOfAirport to something more descriptive like getAirportNameByIataCode.

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

Using ExpressJS with TypeScript: Understanding Request Context

In my TypeScript project, I have encountered certain restrictions when it comes to passing variables through middlewares. Initially, I tried redefining requests using interfaces, but this approach felt implicit and could potentially lead to new problems. ...

Trouble encountered with uploading files using Multer

I am facing an issue with uploading images on a website that is built using React. The problem seems to be related to the backend Node.js code. Code: const multer = require("multer"); // Check if the directory exists, if not, create it const di ...

Which TypeScript type must be used to define a class as a prop in the script setup of Vue 3?

Currently, I am working on a Vue 3 single file component that utilizes the script setup method. The challenge I am facing involves defining a prop that should accept values similar to those passed to the HTML class attribute. This means the prop could be a ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

Scope Error in VueJS Project with TypeScript

I'm facing an issue in my VueJS project with TypeScript where my vue files are divided into HTML, CSS, TS, and vue. The error message I'm getting is: Property '$router' does not exist on type '{ validate(): void; }' Here is ...

Angular chat integration

In my application, I have a parent component called "chat" with two child components - "sidebar" (which displays the user list) and "conversation detail" (which shows the chat with each user). The functionality I am aiming for is that when a user is clicke ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

How to retrieve a value only if it is truthy in JavaScript or TypeScript - Understanding the operator

In React components, a common scenario arises with code like this: <Carousel interval={modalOpen ? null : 8000}> It would be great if I could simplify it to something along these lines (although it's not valid): <Carousel interval={modalOpen ...

Describing data types in TypeScript, when an <Array> contains various structures

I recently started using TypeScript and I'm working on eliminating all instances of any types. Issue: In my React Component, I iterate over an array of objects to extract key/value pairs. The component is passed the following props: tags, tagKeys ...

Troubleshooting Angular 14 Custom Form Control Display Issue

I'm facing an issue while attempting to develop a custom form control in Angular 14. Despite no errors showing up in the console, my custom control is not rendering as expected. When inspecting the Elements tab in the console, I can see the parent com ...

Calendar Component in Angular 2 Written in Typescript and Javascript

Is there a way to calculate the number of working days, excluding Saturdays and Sundays, within a specific month and year? For example: If we choose the year 2017 and the month of February, the output should look like this: { week1 : 3 days[working days ...

A guide on setting up Webpack to directly load a module from its source folder rather than the distribution folder

Currently, I am involved in a monorepo project and I need Webpack to fetch my source files from the src directory instead of the dist folder (as specified in the package.json file). Let's consider the structure below: /packages/core/dist/index.js (c ...

What is the best practice for making a gRPC call within a Typescript Vue.Js component?

Upon reviewing the grpc documentation, I discovered that proto files can be used to generate Node (Javascript), Typescript with the assistance of grpc_tools_node_protoc_ts, and grpc-web. Given that performance is not a critical factor in my particular situ ...

Switch statement with reduced scope for factory

How can I narrow the type output of a factory create method using literal types? I've tried narrowing with if statements and discriminated unions, but since this is a creational method, I'm not sure if it's possible. class Radio { type: ...

A function in Typescript that dynamically determines its return type based on a specified generic parameter

Currently, I am attempting to create a function where the return type is determined by a generic argument. Let me share a code snippet to illustrate: type ABCDE = 'a' | 'b'; function newFunc<U extends ABCDE>(input: U): U extends ...

When working with Typescript, utilizing `null as string | null` can result in a parsing error that says, "Unexpected token, expected ``,`."

Currently, I am going through a React Toolkit tutorial that incorporates Typescript. During this process, I encountered the usage of initialState: null as string | null, within the code example provided and explained at this specific point in the video: c ...

When attempting to upload a file in Vue Apollo, a Node crash occurs with the error message "Maximum call stack size

I've been working on setting up the front end for graphQl file upload with Apollo-boost-upload. The backend code I'm using is based on this helpful tutorial: https://dev.to/dnature/handling-file-uploads-with-apollo-server-2-0-14n7. After adding t ...

"Concealing a column in a PrimeNG data table with dynamic columns: A step-by-step

Hi, I'm looking for a way to hide a column in my PrimeNG data table. Is there an attribute that can be used to turn off columns in PrimeNG data tables? .Html <p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]=" ...

Tips on sorting a nested array in a React TypeScript project

Hey there! I currently have a working filter in React that utilizes a List (I am using Mantine.dev as my CSS template): <List> {locations.filter(location => { const locServices: Service[] = []; location.services.forEach(service => { ...

"Exploring the advancements in inner calls and the deprecation of forkJoin

Here is the code snippet I am currently working with: ngOnInit(): void { this.issueService.getIssues().pipe( switchMap(issues => { this.issuesList = issues; const observables = this.issuesList.map(issue => this.issueService.getChild ...