Reputation: 565
I'm trying to use Spotify API and to move into the Arrays.
const App = () => {
const [isLoading, setIsLoading] = useState(true);
const [dataSource, setDataSource] = useState();
useEffect(() => {
return fetch("https://api.spotify.com/v1/me/albums?offset=0&limit=5", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization:
"Bearer AUTH CODE "
}
})
.then(response => response.json())
.then(responseJson => {
setIsLoading(false);
// console.log(responseJson);
// let result = Object.values(responseJson); // if I want to convert it in array
let result = responseJson
setDataSource(result);
});
}, []);
console.log(dataSource);
and I get an object
{href: "https://api.spotify.com/v1/me/albums?o`enter code here`ffset=0&limit=5", items: Array(5) ...}
I would like to go into items but when i do
console.log(dataSource.items);
or
console.log(dataSource.items[1]);
I get
Cannot read property 'items' of undefined
Any idea? Where is my mistake?
Upvotes: 1
Views: 103
Reputation: 15166
The dataSource
state is by default undefined
, you need to change the default value to have items
property. The fetch
is handling the then
asynchronously so the data will arrive few milliseconds later and in that time the code tries to access items
property which is missing.
You can try to initialize differently, like the following:
const [dataSource, setDataSource] = useState({ items: [] });
I hope this helps!
Upvotes: 1