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
  • 572
  • 5
  • 16
  • 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
  • 4,303
  • 2
  • 20
  • 29
  • Let me know here if you face any problem – moshfiqrony Aug 20 '21 at 17:21
  • Thanks!! When I map {breeds} I get this error: Objects are not valid as a React child (found: object with keys {affenpinscher, african, airedale, akita, appenzeller, australian, – Ricardo de Paula Aug 20 '21 at 17:30
  • That can happen when your ```breedsList.message``` is not holding a single value. It is adding an object. – moshfiqrony Aug 20 '21 at 17:38
  • That is a mapping or iterating issues not a state update issues. Can you show how you are rendering the state. Because in console log it won't give the error you mentioned. When you are trying to render an object that time it is giving the error – moshfiqrony Aug 20 '21 at 17:43
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
  • 314
  • 2
  • 5