javascript - Why am i getting and empty array when fetching an api with react hooks? - Stack Overflow

I am new with react hooks, i'm trying to get info from an API but when i do the request i get 2 re

I am new with react hooks, i'm trying to get info from an API but when i do the request i get 2 responses first an empty array and then the data of the API, why am i getting that empty array! , this is my first question, i'm sorry. Thanks for helping me !

import {useState, useEffect} from 'react';

const getSlides = (API) => {

    const[data,setData] = useState([]);

    const getData = () =>
    fetch(`${API}`)
        .then((res) => res.json())
    
    useEffect(() => {
        getData().then((data) => setData(data))
    },[])




    return data
}

export default getSlides;

I am new with react hooks, i'm trying to get info from an API but when i do the request i get 2 responses first an empty array and then the data of the API, why am i getting that empty array! , this is my first question, i'm sorry. Thanks for helping me !

import {useState, useEffect} from 'react';

const getSlides = (API) => {

    const[data,setData] = useState([]);

    const getData = () =>
    fetch(`${API}`)
        .then((res) => res.json())
    
    useEffect(() => {
        getData().then((data) => setData(data))
    },[])




    return data
}

export default getSlides;

Share Improve this question edited Oct 30, 2020 at 2:42 Joseph D. 12.2k4 gold badges39 silver badges71 bronze badges asked Oct 30, 2020 at 2:33 Diego Fernando Benavides ArizaDiego Fernando Benavides Ariza 211 silver badge4 bronze badges 1
  • You're not printing the API response, you're printing the state value. Which is initially an empty array, THEN gets populated with the API response data. – Jayce444 Commented Oct 30, 2020 at 2:41
Add a ment  | 

4 Answers 4

Reset to default 3

The useEffect() hook runs after the first render. Since you've initialized the data state with an empty array, the first render returns an empty array.

If you're ponent depends on data to render, you can always conditionally return null until your data is loaded.

Also, I remend using an async function for api requests, it allows you to use the await keyword which makes your code easier to read. The only caveat, is that you cannot pass an async function to useEffect, instead define an async function inside your hook, and then call it.

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

const API = "https://example./data";

const GetSlides = (props) => {
  const [data, setData] = useState();

  useEffect(() => {
    async function getData() {
      const request = fetch(API);
      const response = await request;
      const parsed = await response.json();
      setData(parsed);
    }

    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (data === undefined) {
    return null;
  }

  return <>data</>;
};

export default GetSlides;

Of course, you can still use Promise chaining if you desire.

  useEffect(() => {
    async function getData() {
      await fetch(API)
        .then((res) => res.json())
        .then((data) => setData(data));
    }
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
<GetSlides api="https://yay." />

react ponents need to be title case

import React, { useState, useEffect } from 'react'

const GetSlides = ({ api }) => {
  const [data, setData] = useState(null)

  const getData = async () =>
    await fetch(`${api}`)
      .then((res) => res.json())
      .then((data) => setData(data))

  useEffect(() => {
    getData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  console.log(data)

  return <div>slides</div>
}

export default GetSlides

The effect callback function is called after the render of your ponent. (Just like ponentDidMount) So during the first render phase, the data state has not been set yet.

You initialize your data with and empty array here:

const[data,setData] = useState([] <- empty array);

useEffect runs after your ponent is mounted, and then calls the API, that it might take a few seconds or minutes to retrieve the data, but you return the data right away before knowing if the API finished its call.

If you want to return the data after it has been retrieved from the API, you should declare and async method

const getSlides = async (API) => {
 try {
  const res = await fetch(API);
  const data = await res.json();

   return data;
  } catch (e) {
    throw new Error(e);
  }
}

Note that it is not necessary hooks for this function

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745322002a4622483.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信