Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead (React)

Issue

I want to display this "What" in my React App but I still get the same error. It actually logs it in the console but on the page there’s always the same error:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead (React)

Express Route:

const express = require('express');
router = express.Router();

router.get("/", (req, res) => {
    res.send("What")
});

module.exports = router;

React Component:

import React from 'react';

class Login extends React.Component {
    render() {
        function BackendRes() {
            const response = fetch("/login")
                                .then(res => res.text())
                                .then(text => console.log(text));
            return response;
        }
        return (
            <div>
                <BackendRes />
            </div>
        )
    }
}

export default Login;

Solution

Use componentDidMount life cycle method to invoke the api during the initial rendering only. Then set the state to keep the data coming from the api as follows. Then use the state to show the text inside a div.

import React from "react";

class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: "",
    };
    this.BackendRes = this.BackendRes.bind(this);
  }

  componentDidMount() {
    this.BackendRes();
  }

  BackendRes() {
    const response = fetch("/login")
      .then((res) => res.text())
      .then((text) => {
        this.setState({ data: text });
        console.log(text);
      });
  }

  render() {
    return <div>{this.state.data}</div>;
  }
}

export default Login;

Answered By – Kavindu VIndika

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published