Home > Net >  What is the error "options.map is not a function"?
What is the error "options.map is not a function"?

Time:10-24

import React, { useState } from 'react'
export const BreedsSelect = props => {
  const [selectedBreed, setSelectedBreed] = useState(null)

  const options = props.breeds

  return (
    <div>
      <select
        value={selectedBreed}
        onChange={e => setSelectedBreed(e.target.value)}
      >
        {options?.map(breed => {
          ;<option>{breed}</option>
        })}
      </select>
    </div>
  )
}

In the above code I get an error that options.map is not a function. How can this be resolved? The following code calls the above code.

import React, { useEffect, useState } from 'react' // DO NOT DELETE
import { BreedsSelect } from './BreedsSelect'
export const DogListContainer = () => {
  const [breeds, setBreeds] = useState(null)
  useEffect(() => {
    fetch('https://dog.ceo/api/breeds/list/all')
      .then(res => res.json())
      .then(data => {
        setBreeds(data.message)
      })
  }, [])
  return <BreedsSelect breeds={breeds} />
}

CodePudding user response:

You can only map an array, probably breeds is a different data type, if its an object you can try Object.keys(breeds).map or Object.values(breeds).map depending on what you need, check here for more info https://javascript.info/keys-values-entries

CodePudding user response:

The problem is you are trying to map through object properties and you can only map an array. For example, you can map through each of those dog breeds values to get the array information inside of each breed. It looks like you are trying to show the dog breed names. You need to access those with something like

Object.keys(options).map(breed => <option>{breed}</option>)

this should work assuming there is no other bugs in your code.

Object.keys(yourobjectname) goes through the objects properties and returns them in an array. This allows you to map over that array it makes by chaining .map() to the end.

There is also an Object.entries and Object.values you should get to know.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

  • Related