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

160
Visualizações
Await fetch returns 2 arrays and data can't be used

I'm working on a full-stack project using Express in back-end and react in front-end. Now the problem is with a specific component. It is supposed to fetch the results of a database query from /api/blogposts. But then it goes wrong.

here's my code:

import React from 'react';
import './Blogposts.css';
import SingleBpost from '../SingleBpost/SingleBpost.js';

class Blogposts extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            receivedPosts: []
        };
    }
    async getBpostsFromServer() {
            const response = await fetch("/api/blogposts");
            let myPosts = await response.json();
            this.setState({receivedPosts: myPosts});
        }
    componentDidMount() {
        this.getBpostsFromServer();
    }
    render() {
        console.log(this.state.receivedPosts);
        return(
            <div id="Blogposts">
            <SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
            </div>
        );
    }
}


export default Blogposts;

There is only one console.log: console.log(this.state.receivedPosts); but the console gives me two results: first it prints an array that I don't recognize, then it prints the array that I need. (here's a screenshot https://imgur.com/a/q40aVkq).

But when I try to feed the data from this.state.receivedPosts into my component like this:

<SingleBpost title={this.state.receivedPosts[0].title} (etc etc) />

It doesn't work (my screen sctually turns blank).

Does anyone have any idea as to what I'm doing wrong here? Thanks for any help!

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

0

You can use && which will protect you from that case

render() {
        return (
            this.state.receivedPosts && this.state.receivedPosts.length
            <div id="Blogposts">
            <SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
            </div>
        );
    }

Or handling it via ternary operator:

 render() {
            return (
                this.state.receivedPosts && this.state.receivedPosts.length ?
                <div id="Blogposts">
                <SingleBpost title="Test" date="18/12/2021" author="Kepos Team" body="Hello, this is a test for the blogposts!" />
                </div> : null
            );
        }
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