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?

4
  • 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). 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? Commented Aug 18, 2020 at 13:29
  • 1
    should it be axios.get(....)? Commented Aug 18, 2020 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 Commented Aug 18, 2020 at 13:35
  • I think you can await setAlbums(result.data.topalbums); Commented Aug 18, 2020 at 13:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.