Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda