0

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?

pilchard
  • 12,414
  • 5
  • 11
  • 23
Spartis
  • 51
  • 6
  • your are logging using concatenation which coerces the objects to strings `console.log('in fetch ' + certificateTypes);`. You can either separate with a comma `console.log('in fetch: ', certificateTypes);` or explicitly stringify `console.log('in fetch ' + JSON.stringify(certificateTypes, null, 2));` – pilchard Apr 29 '23 at 17:38
  • Does this answer your question? [Javascript console.log(object) vs. concatenating string](https://stackoverflow.com/questions/14597246/javascript-console-logobject-vs-concatenating-string) – pilchard Apr 29 '23 at 17:40
  • The data is already in an array. – pilchard Apr 29 '23 at 17:42

2 Answers2

2

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);

Rupali Yadav
  • 121
  • 4
1

Simply change your console.log to:

console.log('in fetch ', certificateTypes);
Thomas Frank
  • 1,404
  • 4
  • 10