Alex
Alex

Reputation: 1

How can I use a Promise in React props?

I am getting data from the server and I want to change the number data to a string. sub code like

{
    title: 'stage',
    dataIndex: 'stage',
    render:  (text, record, index) => {
        return (
            <Tag> {getBookItem(TASK_STAGE, text)} </Tag>
        );
    },
} 
const getBookItem = async (key, text) => {
var data = await getSysData();
var str = '';
data[key].forEach((element) => {
    if (element.id == text) {
        str = element.value;
    }
});
return str;}
const getSysData = async () => {
return await markBook()};

the function getBookItem returns a 'Promise', so I get an error like

 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 can‘t make this function not async, because I use axios to get data. And I can't use Prmoise in react props, so How can I change this data

Upvotes: 0

Views: 2170

Answers (1)

Ahmet Ulutaş
Ahmet Ulutaş

Reputation: 227

You can not render an async function directly in the JSX because it returns a promise. You should store the returned value in a variable and try to render it. I am sharing an example code block for you. Please try to discover your mistake by comparing.

import React from 'react';

export default function App() {

  const [first, second] = [2, 4];
  let result;
  const sum = async (a, b) => (result = a + b);

  sum(first, second); // call the function somewhere you need, (usually in useEffect)

  return (
    <div>{result}</div> {/*  renders 6  */}
  );
}

Upvotes: 1

Related Questions