pokelkrique
pokelkrique

Reputation: 33

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

Upvotes: 1

Views: 1002

Answers (1)

Nizar
Nizar

Reputation: 722

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.

Upvotes: 1

Related Questions