Search code examples
javascriptreactjstypescriptnext.jsfetch

Next.JS/React Objects are not valid as a React child


TL;DR
I have an error Error: Objects are not valid as a React child (found: [object Promise]) due to a fetch request in the code. The project is written in Typescript and when I try the same code snippet in another project (Javascript), I don't get the error.

So I have been working on a project and when I try to send a POST request via fetch, I get the 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.. I think that the metadata in the fetch method is causing this error, but I don't think that there is a way around it. I checked if it was just an error so I compared it to another request in one of my other projects, and it copied its code to my current project. And I still got the same error! Could it be because my current project is written in typescript?

// This is Typescript
//It's also the same code as my other project.

import axios from 'axios';
export default async function component() {
  const uri = "http://localhost:3000"
  const data = {
    a: 1,
    b: 2,
    c: 3
  }
  async function sendRequest() {
     await fetch(`${uri}/api/getPasswords`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({data}),
    }).then(e => {
      console.log(e);
    }).catch(error => {
      console.log(error)
    })
  }
  return (
    <div>
      <button onClick={sendRequest}>Send POST request</button>
    </div>
  );
}

Solution

  • The issue is, you are using async on your React component. Follow these steps:

    1. Remove async keyword from the React component
    2. Make the component name start with uppercase (component -> Component)
    3. Use axios instead of fetch and use trycatch (optional)
    import axios from 'axios'
    
    async function sendRequest() {
      try {
        const res = await axios.post(`${uri}/api/getPasswords`, data)
        console.log(res.data)
      }
      catch(err) {
        console.log(err)
      }
      
    }