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

89
Visualizações
How to setState with fetched data in React

I need to setState with an object that I'm getting from a redux store. The problem is when I call setState in my component I am getting undefined. Any idea on how to set a default value of state with fetched data?

Here is my component:

import React, { useEffect, Fragment, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

const contactDetails = useSelector((state) => state.contactDetails)

const upFields = contactDetails?.contact?.data?.fields


const [contact, setContact] = useState({
    fields:  upFields <---- this is returning undefined.. The name is correct, but maybe setState is running too fast? 
  })
  

console.log(contact) <---- this shows {fields: undefined}



console.log(upFields) <---- this console.logs just fine
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you use useEffect() and trigger it using the object

useEffect(()=>{
  setContact(fetched_data)
}, [fetched_data]) // <-- data array will trigger every time this data change

you can trigger it on first component mount with

useEffect(()=>{
  setContact(fetched_data)
}, []) // <-- empty array will only trigger once
about 4 years ago · Juan Pablo Isaza Relatório

0

So, I ended up setting my state one component higher, and passing the "upFields" to the child component that needed this state. Once in the child component I just ran a useEffect and setState with the data I needed

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