Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Fetch data changing on reload from array to undefined

I'm getting some weird error. Just starting with typescript. When i write console.log(data) for the first time i get an array with objects inside. The problem occurs when i reload the webpage without touching anything. My console log returns undefined.

const Home = (): JSX.Element => {
  const [data, setData] = useState<any>();
  const [loading, setLoading] = useState<boolean>(true);
  const fetchApi = () => {
    fetch("https://fakestoreapi.com/products")
      .then((res) => {
        return res.json();
      })
      .then((data) => setData(data));
      console.log(data)
  };
  useEffect(() => {
    fetchApi();
    setLoading(false);
  }, []);
  return(
      <div>

      </div>
  )
};

Return of first console.log First log

After reload Log after refreshing page (no code changed)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you need to console.log inside "then"

.then((data) => {
   setData(data));
   console.log(data)
})

if you console.log the data state under setData it will show undefined, you can console.log(data) state inside useEffect after fetchApi()

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!