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

113
Views
State undefined even with initial state in React

I declared a state named product with initial values. However it appears as undefined once before loading the new values. This causes problems when I want to map its value.

import React, { useEffect, useState } from 'react';
import './App.css';
import { useQuery, gql } from "@apollo/client";
import { LOAD_PRODUCT } from "./GraphQL/Queries";

import Product from './Components/Product';

function App() {

    const { error, loading, data } = useQuery(LOAD_PRODUCT)
    const [product, setProduct] = useState<Product>({
      node: {
        id: 0,
        title: "Test"
      }
    })
    
    useEffect(() => {
         setProduct(data)
     }, [data])


    if(loading) return <h1>Loading...</h1>

    console.log(product)

  return (
    <>
    <Product product={product}/>
    </>
  );
}

export default App;

enter image description here

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

0

So I'm assuming data is undefined before it's fetched from your database. And therefore loading returns true meanwhile. Since loading = true before data is available, your component is returning <h1>Loading...</h1>. And therefore is not reaching your console.log(product) . I suspect that if you move console.log(product) to right before the if(loading) return <h1>Loading...</h1>, you'll get the result you need. So in the beginning it WILL print out the initial value, however it will change the initial value to undefined (using setProduct) after that, and finally when the data is fetched it'll setProduct to the data. Let me know if that works out for you, I played with the code a little bit on my end.

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!