0

I am trying to render data from rest api site, I can get all info without issues, but is duplicating the data with an empty array first and this is creating a conflict with the map() function.

when I do a console logo I can see the duplication. what I need is to only get the array that has the data and the empty one or how can I select the array with data, since for somereason when i used the map() function I get error because its reading the empty array

duplication

useFetchData.js

import { useEffect, useState} from 'react';
import http from '../../services/httpservices';
import config from '../../services/config.json';

const useFetchData = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);

 useEffect(() => {
 const fetchData = async () => {
  try {
    const { data: response } = await http.get(config.apiEndpoint);
    setData(response);
  } catch (error) {
    console.error(error)
  }
   setLoading(false);
  };

   fetchData();
  }, []);
 return {
  data,
  loading,
 };
};

export default useFetchData;

customsite.jsx

  import React, { useState } from 'react';
  import Modal from './reusable/modal';
  import useFetchData from './hooks/useFetchData';

  const Customsite = ()=> {

const {
    data,
    loading,
  } = useFetchData();


  console.log(data);

return(
    <div>
     <p> we here </p>

            
               </div>
     )
     }

  export default Customsite

1 Answer 1

1

you only need to wait until the data has loaded to get the full array, you must condition the console log to loading === false


!loading && console.log(data);

the same goes with the map function you want to use. you need to add this condition. Either that or test if data.length > 0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.