1

This is my code,

import React, { useState, useEffect } from "react";
import axios from "axios";

import "./App.css";

function App() {
  let [albums, setAlbums] = useState([]);
  useEffect(() => {
    const key = "blablabla to keep secret";
    const fetchData = async () => {
      const result = await axios(
        `http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=cher&api_key=${key}&limit=10&format=json`
      );

      setAlbums(result.data.topalbums);
      console.log(albums, "data?");

      // const { data } = props.location.state;
    };

    fetchData();
  }, []);
  return <div className="App"></div>;
}

export default App;

the data I am fetching is in an object with objects inside, in-state I initialized with an empty array, and then after I fetched the data I use setAlbums. I have two problems, the console.log after I fetch just shows me an empty array, but when I console log in render I do get the data but it is an object and not an array of objects, so I can't even map over it, how do I fix this?

SwissLoop
  • 466
  • 2
  • 11
  • In reference to the empty console.log, this is expected. The state update will not take place immediately after the updater function is called (see [this answer for more](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately)). In reference to the data being an object and not an array, I can't really say. Is the response from the `axios` request an array? – Brian Thompson Aug 18 '20 at 13:29
  • 1
    should it be axios.get(....)? – Prateek Thapa Aug 18 '20 at 13:30
  • no the response is a object, but i want to put it in an array, so i can map over it.. that is why i initialised state with empty array, so that is my main problem right now, i'm very new to hooks – lydia michael Aug 18 '20 at 13:35
  • I think you can `await setAlbums(result.data.topalbums);` – Aman Aug 18 '20 at 13:35

1 Answers1

1

Try to do something like this:

setAlbums(album => [...album, results.data.topalbums])

that way you can push results to your array instead of transforming it into object

also if you wish to see updated album then create something like:

useEffect(() => {
console.log(albums)
},[albums])

as setting state is asynchronous therefore it doesn't happen immediately as Brian mentioned, so this code will launch if albums state changes its value

Zirek
  • 513
  • 3
  • 11
  • 20