Skip to content
Advertisement

What is the error “options.map is not a function”?

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} />
}

Advertisement

Answer

im trying it and it cause of the data was late to read and the browser was too fast to read it so i tryin with this

import React, { useEffect, useState } from "react"; // DO NOT DELETE
import { BreedsSelect } from "./BreedsSelect";
export const DogListContainer = () => {
  const [breeds, setBreeds] = useState(null);
  useEffect(() => {
    const fetchAll = async () => {
      try {
        const data = await fetch("https://dog.ceo/api/breeds/list/all");
        if (!data.ok) throw new Error("error");
        return data;
      } catch (error) {
        return error;
      }
    };

    fetchAll()
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        setBreeds(data.message);
      });
  }, []);
  return <BreedsSelect breeds={breeds} />;
};

idk if it woukd be helps u or no

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement