JithinAji
JithinAji

Reputation: 489

Fetching json api using react ( useeffect )

Hellooo,

This is my first time using React. I want to fetch some data in json format and list it out in my page. The code below is not working.

import React, { useState, useEffect } from "react";
import axios from "axios";

function DataFetching() {
  const [users, setUsers] = useState({ hits: [] });
  //const [query, setQuery] = useState("redux");

  useEffect(async () => {
    const fetchData = async () => {
      const result = await axios("url");
      setUsers(result.data);
    };
  }, []);

  return (
    <div>
      <p>Hellooooo</p>
      <ul>
        {users.hits.map((user) => (
          <li key={user.id}>{user.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default DataFetching;

Upvotes: 0

Views: 948

Answers (1)

Drew Reese
Drew Reese

Reputation: 202741

Issue

  1. useEffect hook callbacks are 100% synchronous, they can't be asynchronous (i.e. declared async) at all. This also implicitly returns a Promise and messes with the effect cleanup functionality.
  2. Your code never calls the fetchData function, so nothing is really updated.
  3. You stomp your state shape and place the result array at the root state level instead of in an object under the hits key.

Solution

  1. Remove the async keyword from the effect callback.
  2. Invoke fetchData in the effect callback body.
  3. Update state correctly.

Code:

useEffect(() => {
  const fetchData = async () => {
    try {
      const result = await axios("url");
      setUsers({ hits: result.data });
    } catch(error) {
      // handle any GET request or response handling errors
    }
  };
  fetchData();
}, []);

Edit priceless-dew-qbhtu

enter image description here

Upvotes: 6

Related Questions