My API gives me data in the following format:
{
status: 200,
certificateTypes: [
{
id: 1,
name: 'Gasmeting',
created_at: '2023-04-25T07:15:55.000000Z',
updated_at: '2023-04-25T07:15:55.000000Z',
},
{
id: 2,
name: 'Mangatwacht',
created_at: '2023-04-25T07:16:13.000000Z',
updated_at: '2023-04-25T07:16:13.000000Z',
},
],
// ...
}
I used the following function to put the data in an useState array.
const [certificateTypes, setCertificateTypes] = useState([]);
const fetchCertificateTypes = async () => {
const response = await getCertificateTypes();
if (response.status === 200) {
setCertificateTypes(response.certificateTypes);
console.log('in fetch ' + certificateTypes);
}
};
Now printing the data with:
console.log(certificateTypes)
gives the following result:
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
My initial thought was that I needed to JSON.parse the data I fetched, but this does not seem to be the case..
How can turn this data into an array so I can properly work with it?
2
Answers
Simply change your console.log to:
When you try to concatenate a string with an certificateTypes variable using the + operator, JavaScript automatically converts the array to a string representation, which is "[object Object]". And the default string representation of an array is "[object Object]".
updating state in ReactJS is an asynchronous process. When you call setState() to update the state of a component, React schedules the update to occur in the future, rather than updating the state immediately. This means here when you console.log(‘in fetch ‘ + certificateTypes); the updated state may not be immediately available after calling setCertificateTypes(response.certificateTypes).
to console.log your certificateTypes, write a console.log(certificateTypes) before you return a jsx (or anywhere outside useEffect);