Reputation:
I trying to fetch an array and update state using hooks
const [items, setItems] = useState([]);
const getItems = async () => {
try {
const response = await apiLink.get('...');
const data = response.data;
console.log(data) // show an array of objects
setItems(data);
console.log(items); // show empty array
} catch(error) {
//...
}
};
console.log(data):
Array [
Object {
"id": "1",
"name": "Item name 1",
"score": 10,
},
Object {
"id": "2",
"name": "Item name 2",
"score": 12,
},
]
console.log(items): Array []
I also tried to use const responseJSON = response.json()
, but there is an error occurs
response.json is not a function. (In 'response.json()', 'response.json' is undefined)
What do i wrong?
Upvotes: 0
Views: 1904
Reputation: 21
The seItems
function here is asynchronous try keeping the log in useEffect hook you'll get the result
Upvotes: 0
Reputation: 552
setItems
here will be called acynchronously, so would not see anything in the console just yet. However if you want to do some computation after the state for items is set, you can use a callback function using useEffect
.
You can read more here for how to use setState Callback in a Functional Component.
Upvotes: 1
Reputation: 1405
Your component should seem something like :
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState({ hits: [] });
useEffect(async () => {
const result = await apiLink.get('...');
setData(result.data);
});
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
export default App;
Upvotes: 0