1

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>
  );
}
1
  • 1
    Try removing the async in export default async function component(). Commented Aug 14, 2021 at 9:10

2 Answers 2

2

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)
  }
  
}
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is not related to Typescript, you're trying to use a Promise as a React Component, first, resolve the Promise and then send the data you need as a proper React Component.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.