0

How do I place this object inside an array: Dog API. Is an object inside another object. I'm trying to set setBreeds(breedsList.message) but does not work.

const basicUrl = `https://dog.ceo/api/breeds/`
const listUrl = `list/all`

const Home = () => {
  // uses state to store the list of breeds
  const [breeds, setBreeds] = useState([])

  // fetch the list of breeds
  const fetchBreeds = async () => {
    let url
    url = `${basicUrl}${listUrl}`
    const response = await fetch(url)
    const breedsList = await response.json()
    setBreeds(breedsList)
  }

  // useeffect to mount the fetchBreeds function
  useEffect(() => {
    fetchBreeds()
  }, [])

  return (
    <div>
      {/* // maps  */}
      {breeds.map((breed) => console.log(breed))}
    </div>
  )
}

export default Home
Ricardo de Paula
  • 444
  • 3
  • 14
  • 1
    Does this answer your question? [Correct modification of state arrays in React.js](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js) – imjared Aug 20 '21 at 17:10

2 Answers2

1

You do like this

setBreeds(prevState => [...prevState, breedsList.message])
moshfiqrony
  • 2,887
  • 15
  • 25
0

I'm not sure if that is what you are asking for but the following function turns the json response into a list of breed names. You could transform the object and then call setBreeds.

function transformToList(breedsResponse) {
    const {message: breeds} = breedsResponse;
    const breedMainNames = Object.keys(breeds);
    return breedMainNames.reduce((acc, mainName) => {
        const subNames = breeds[mainName];
        if(subNames.length === 0) {
            acc.push(mainName)
        } else {
            const combinedNames = subNames.map(name => `${name} ${mainName}`);
            acc.push(...combinedNames);
        }

        return acc;
    }, [])
};
Ali Baykal
  • 196
  • 1
  • 5