0

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?

3 Answers 3

1

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.

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

Comments

0

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;

Comments

0

The seItems function here is asynchronous try keeping the log in useEffect hook you'll get the result

Comments

Your Answer

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