Bussiere
Bussiere

Reputation: 1152

e.results.map is not a function in typescript3

here is my code :

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

and 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

but i get a Uncaught TypeError: e.results.map is not a function :

enter image description here

So the error is in mapping my result in suggestion but how to correct this ?

The result of the api is :

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

So i ddon't have any ideas on how to correct this error to map correctly the result of the call of the api to the suggestion.

Upvotes: 0

Views: 108

Answers (1)

&#196;lskar
&#196;lskar

Reputation: 2577

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

The data object you are accessing is not an array. Thus, you cannot directly use Array prototype methods (like map) on object literals.

You'll either need to return an array from your API or change your code to iterate over the object appropriately like:

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

Upvotes: 1

Related Questions