admin管理员组

文章数量:1278948

Code in "/pages/blog/index.js" :

import BlogComponents from "../../ponents/Blog/blogComponents";
import { listBlogs } from "../../server/mongodb";

const index = async (props) => {
  console.log(props)
  return (
    <div>
      <Head>
        <title>BLOG TITLE</title>
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" />
      </Head>
      <h1>BLOG HEADER</h1>
      <BlogComponents />
    </div>
  );
};

export async function getServerSideProps() {
  var blogs = await listBlogs();
  try {
    return {
      props: { blogs }
    }
  }
  catch (error) {
    console.log(error);
  }
}
export default index;

Code in "../../server/mongodb.js":

import mongoose from "mongoose";
// URI for mongodb
const uri = process.env.MONGODB_URI
const options = { useNewUrlParser: true, useUnifiedTopology: true }

// Mongoose Client Promise
mongoose.connect(uri, options)
import {Blog} from "./mongooseModels/blogModel";

export async function listBlogs() {
    let blogs = await Blog.find().lean();
    //console.log(JSON.stringify(blogs));
    
  return JSON.stringify(blogs);

}

End goal is to get all blog posts with their properties and integrate them into a react/nextjs ponent. A console.log to the "props" argument in index.js returns:

{
  blogs: `[{"_id":"HEXID","title":"Blog Title","author":"ME","date":{"day":"27","month":"January","year":"2021"},"image":"/images/image.jpg","alt":"image alt","summary":"blog summary","content":["blog content "]},{"_id":"61f8c1953907a8bef3dcb4ff","title":"Blog Title 2","author":"ME","date":{"day":"27","month":"January","year":"2021"},"image":"/images/image.jpg","alt":"image alt","summary":"blog summary","content":["blog content"]}]`
}

Current error is: 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. However the page is able to recieve the data returned from getServerSideProps()

** EDIT / Solution ** Figured it out... The error was not ing from the return statement in getServerSideProps(). It was instead ing from the ponent. In preparation for connecting to a DB, I added, "async" to the ponent which in turn started throwing the error. Disappointed that NextJS wouldn't tell you where the "promise" is ing from in the returned error.

Code in "/pages/blog/index.js" :

import BlogComponents from "../../ponents/Blog/blogComponents";
import { listBlogs } from "../../server/mongodb";

const index = async (props) => {
  console.log(props)
  return (
    <div>
      <Head>
        <title>BLOG TITLE</title>
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" />
      </Head>
      <h1>BLOG HEADER</h1>
      <BlogComponents />
    </div>
  );
};

export async function getServerSideProps() {
  var blogs = await listBlogs();
  try {
    return {
      props: { blogs }
    }
  }
  catch (error) {
    console.log(error);
  }
}
export default index;

Code in "../../server/mongodb.js":

import mongoose from "mongoose";
// URI for mongodb
const uri = process.env.MONGODB_URI
const options = { useNewUrlParser: true, useUnifiedTopology: true }

// Mongoose Client Promise
mongoose.connect(uri, options)
import {Blog} from "./mongooseModels/blogModel";

export async function listBlogs() {
    let blogs = await Blog.find().lean();
    //console.log(JSON.stringify(blogs));
    
  return JSON.stringify(blogs);

}

End goal is to get all blog posts with their properties and integrate them into a react/nextjs ponent. A console.log to the "props" argument in index.js returns:

{
  blogs: `[{"_id":"HEXID","title":"Blog Title","author":"ME","date":{"day":"27","month":"January","year":"2021"},"image":"/images/image.jpg","alt":"image alt","summary":"blog summary","content":["blog content "]},{"_id":"61f8c1953907a8bef3dcb4ff","title":"Blog Title 2","author":"ME","date":{"day":"27","month":"January","year":"2021"},"image":"/images/image.jpg","alt":"image alt","summary":"blog summary","content":["blog content"]}]`
}

Current error is: 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. However the page is able to recieve the data returned from getServerSideProps()

** EDIT / Solution ** Figured it out... The error was not ing from the return statement in getServerSideProps(). It was instead ing from the ponent. In preparation for connecting to a DB, I added, "async" to the ponent which in turn started throwing the error. Disappointed that NextJS wouldn't tell you where the "promise" is ing from in the returned error.

Share Improve this question edited Feb 2, 2022 at 4:13 slay3r9903 asked Jan 29, 2022 at 2:01 slay3r9903slay3r9903 911 gold badge1 silver badge5 bronze badges 11
  • Try to set a variable first for the promise. const blogs = await Promise.all(blogArr) and then set blogsDB : blogs. – Arcanus Commented Jan 29, 2022 at 2:14
  • Right now your returning the Promise object. – Arcanus Commented Jan 29, 2022 at 2:15
  • 1 Where is getServerSideProps called/used? Can you update to include a minimal, plete, and reproducible code example? You've also a lot of waiting for things that aren't asynchronous in that function. Can you also share what listBlogs is? – Drew Reese Commented Jan 29, 2022 at 2:22
  • 1 Please share the React ponent code for that page. – juliomalves Commented Jan 29, 2022 at 2:37
  • 1 @drewReese I added the whole index.js I'm not doing anything really with the input from the DB yet. Waiting on having something working e through, before I do more work on the page. – slay3r9903 Commented Feb 1, 2022 at 23:59
 |  Show 6 more ments

2 Answers 2

Reset to default 7

Your index blog ponent should not be declared async. React function ponents are pure, synchronous functions.

const index = async (props) => { // <-- implicitly returns Promise object
  console.log(props)
  return (
    <div>
      <Head>
        <title>BLOG TITLE</title>
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" />
      </Head>
      <h1>BLOG HEADER</h1>
      <BlogComponents />
    </div>
  );
};

export default index; // <-- implicitly returned Promise object

The ponent should a synchronous function.

const index = (props) => { 
  useEffect(() => {
    console.log(props);
  }, [props]);
  
  return (
    <div>
      <Head>
        <title>BLOG TITLE</title>
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <meta httpEquiv="Content-Type" content="text/html;charset=UTF-8" />
      </Head>
      <h1>BLOG HEADER</h1>
      <BlogComponents />
    </div>
  );
};

Yeah, I was getting the same error, couldn't figure it out initially, as the error message is rather ambiguous.

Then I noticed I've declared my react ponent with the async keyword, which returns a Promise and this is what React was plaining about. React functional ponents cannot return promise objects. Otherwise, using async functions within useEffect() works fine.

import { useEffect, useState } from 'react';

const url = 'https://api.github./userssss'; // /users is correct, /usersssss returns error response.

const FetchTest = () => {
// React ponent cannot be promise object, must be pure object
const [users, setUsers] = useState([]);
const [isError, setIsError] = useState(false);

const fetchDataExample = async () => {
// but we can have async functions within useEffect()
try {
  let response = await fetch(url);

  if (!response.ok) {
    setIsError(true); // this is a gotcha, because fetch() doesn't treat 4xx and 5xx as errors,
    // thusly, the catch() block will not run if remote resource is not found. So we need to handle the error response like this as well.
    // If Axios is used, this issue is not present and catch() will run on err.
    return;
  }
  // Order of our code in Javascript does matter, thats why we add our error-checking condition first and only after it
  // we write the rest of our code that handles success response
    let users = await response.json();
    setUsers(users);

    console.log(users);

    return users; // do we need to return anything?
} catch (error) {
    setIsError(true);
    console.log(error.message);
}
};

useEffect(() => {
  fetchDataExample();
}, []);

本文标签: