1

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

2
  • Since it logged after the loading state, it might be the transition of data, not related to initial value. Logging before the loading state should be ok. Please just create a reproducible example in a sandbox. How to create a Minimal, Reproducible Example Commented Oct 3, 2021 at 6:02
  • Moreover you just duplicating the state, there should be some initial value API you can pass to useQuery. Commented Oct 3, 2021 at 6:07

1 Answer 1

1

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.

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.