Reputation:
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} />
}
Upvotes: 0
Views: 1252
Reputation: 38
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
Upvotes: 1
Reputation: 260
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
Upvotes: 0
Reputation: 78
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
Upvotes: 0