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

215
Visualizações
Why does my axios request print in console but doesn't set state

I'm trying to display some data from my database in my React component but the data isn't getting saved in the state hook, but the request's response does print in the console.

How can I fix this?

const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);

useEffect(() => {
  const getCollections = async () => {
    try {
      const response = await axios.get('http://localhost:4000/api/collections');
      setIsLoaded(true);

      console.log(response); // This prints the response
      setCollections(response);
      console.log(collections); // This prints []

    } catch (error) {
      setError(error);
      setIsLoaded(true);
    }
  }

  getCollections();
}, [])

Console logs

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

setCollections is not executed immediately by React. The new state should be available on the next render. Try logging during the render phase:

const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);

console.log(collections);

useEffect(() => {
  ...
}, [])
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