Encountered an issue: e.results.map is not recognized as a function in TypeScript version

Here's the code snippet I am working on:

Search.tsx

import * as React from 'react';
import axios from 'axios'
import Suggestions from './Suggestions'

const API_KEY:string = "process.env"
const API_URL:string = 'http://127.0.0.1:9001/v1/test'

export class Search extends React.Component{
  state = {
  query: '' as string,
    results : [] as any[]
  }
  search = {
    value: '' as string,
    }
  getInfo = () => {
    axios.post(`${API_URL}/${this.state.query}/`)
      .then(({ data }) => {
        this.setState({
          results: data.data
        })
      })
  }

  handleInputChange = () => {
    this.setState({
      query: this.search.value
    }, () => {
      if (this.state.query && this.state.query.length > 1) {
        if (this.state.query.length % 2 === 0) {
          this.getInfo()
        }
      } else if (!this.state.query) {
      }
    })
  }

  render() {
    return (
      <form>
        <input
          placeholder="Search for..."
          ref={input => this.search = input}
          onChange={this.handleInputChange}
        />
        <Suggestions results={this.state.results} />
      </form>
    )
  }
}

export default Search

Suggestion.tsx :

import * as React from 'react';
import { any } from 'prop-types';

export const Suggestions = (props:any) => {
  const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
    <li key={r.id}>
      {r.name}
    </li>
  ))
  return <ul>{options}</ul>
}

export default Suggestions

I encountered a Uncaught TypeError: e.results.map is not a function error.

https://i.sstatic.net/x0G8d.png

The issue seems to be with mapping the result in suggestion component. How can I correct this?

The result obtained from the API is:

{'data': {'0': 'toto', '1': 'titi'}}

I'm unsure how to properly map the result from the API call to the suggestion component.

Answer №1

{'information': {'0': 'toto', '1': 'titi'}}

The information object you are trying to access is not in the form of an array. Therefore, you cannot directly apply methods found in the Array prototype (such as map) on object literals.

You will either have to ensure that your API returns data in an array format or adjust your code to properly iterate over the object like this:

for(key in obj) { 
    console.log(obj[key])
}

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

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

The TypeScript declarations for Forge Viewer do not include typings related to Profiles

I've been utilizing typescript definitions for Forge from the DefinitelyTyped repository: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/forge-viewer However, there seems to be a lack of typings, particularly those associated wi ...

Top Recommendations: Comparing Standalone Components and Modules in Angular Version 14

I'm in need of some clarification on the most effective practices when it comes to utilizing standalone components and modules within Angular 14. With the introduction of standalone components as a new concept in Angular, I am seeking factual guidance ...

What are the two different ways to declare a property?

I am trying to update my interface as shown below interface Student{ Name: String; age: Number; } However, instead of the current structure, I would like it to be like this interface Student{ Name: String; age | DOB: Number | Date; } This means t ...

Angular: Troubleshooting - potential bug in test case with jasmine causing TypeError: Undefined property 'cmd' OrAngular: Debugging

I'm working on writing a unit test case for integrating lotame analytics. Can anyone offer some assistance on how to write a test case for this integration? I've been stuck on this for quite some time now and keep receiving TypeError: Cannot read ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

The rule in tslint requires sources imported within a group to be organized in alphabetical order

Currently, I am working with a setup that involves create-react-app in combination with custom-react-scripts-ts. Below is the code snippet for my component: import * as React from "react"; import "./App.css"; // reset.css import ErrorsContainer from "./ ...

Tips for formatting numbers in Angular 2 using TypeScript

For example, my numeric value is (651156) and I need to format it automatically as (6,51,156), using TypeScript. ...

Using the ng-template-outlet within two separate loops

I am facing an issue where I need to repeat the same code in two different places. The profiles, profile1 and profile2 are arrays. I want to display the same HTML code without duplicating it. profile1 = [{name : 'mr.A1',age : 25 }, {name : &apos ...

What is the proper way to expand an interface by adding an asynchronous function?

Is there a recommended approach for extending an interface with an async function in TypeScript? One useful technique could be adding a property to the async function that acts as a constant, similar to this example. However, there seems to be a challeng ...

Execute various Office Scripts functions within a single script based on the button that is selected

Imagine you have an Excel spreadsheet with two buttons named populate-current and populate-all. Both buttons execute the same Office Script function that looks something like this: function populateByRowIndex(workbook: ExcelScript.Workbook, rowIndex: numbe ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...

Angular TypeScript state management system

I am facing a challenge in connecting a controller to a state (using angular ui.router) where one way of writing it works, while the other does not. Successful example (with the controller registered under the module): this.$stateProvider .state(' ...

Exploring the usage of arrays within Angular 4 components. Identifying and addressing overlooked input

I'm struggling with array declaration and string interpolation in Angular 4 using TypeScript. When I define the following classes: export class MyArrayProperty { property1: string; property2: string; } export class MyComponent { @Input() object: ...

angular select radio group index in mat

Within a loop, I have a radio button in a mat radio group where the button and card should change color based on the selected index. However, as shown in the screenshot, the radio button is selected but not displaying in white. https://i.sstatic.net/epcPy ...

Export full module as a constructor function

Imagine having a nodejs module where requiring it gives you a constructor function. Here's an example: var Mod = require("modulename"); var mod = new Mod(); mod.method(); Now, I want to create a .d.ts declaration file that can be imported and utiliz ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

Every time I attempt to utilize `glidejs`, I encounter the error message stating that "default is not a constructor."

Here is the code snippet I am working with: import Glide from "@glidejs/glide"; const SectionSlider = () => { const UNIQUE_CLASS = "random_string" let MY_GLIDEJS = useMemo(() => { return new Glide(`.${UNIQUE_CLASS}`, { ...

The method toLowerCase is not found on this data type in TypeScript

I am currently working on creating a filter for autocomplete material. Here is an example of my model: export class Country { country_id: number; name: string; } When calling the web method ws: this.ws.AllCountry().subscribe( ...