1
votes

I'm trying to ask my api for a list of ids and display them in Select component of antd.

<Select style={{ width: "100%" }}> 
    {myApi.getIds().then((result) => result.map((value) => {
        return <Select.Option value={value}>{value}</Select.Option>
    }))}                                               
</Select>

value is string.

getIds returns Promise<string[]>

This returns an error Objects are not valid as a React child (found: [object Promise]). But the value is just a string with an id. What am I missing here?

EDIT: Don't know if it will help anyone, but my solution, based on the accepted answer is:

const [ids, setIds] = useState<string[]>(null);

useEffect(() => {
    //some code
    if (!ids) {
        myApi.getIds().then((result) => setIds(result));
    }
// some code
return () => { };
}, [ids]);

// some more code
return (
    <>
    //render other elements
    <Select style={{ width: "100%" }}>
        {ids?.map((value) => {
            return <Select.Option value={value}>{value}</Select.Option>
        })}
    </Select>
    //render other elements
</>
);
1

1 Answers

2
votes

It's not complaining about value, it's complaining about the the return value of then.

<Select style={{ width: "100%" }}> 
    {myApi.getIds().then((result) => result.map((value) => {
// −^^^^^^^^^^^^^^^^^^^^
        return <Select.Option value={value}>{value}</Select.Option>
    }))}                                               
</Select>

The return value of then is a promise.

You can't render the result of calling getIds like that. Instead, you'll need to either:

  1. Do the getIds in the parent component and have that component pass the result (when it's available) to this component as a prop,

    or

  2. Have this component do getIds and wait for the result in a useEffect callback (functional component w/hooks) or componentDidMount (class component), save the result in state, and use that state when rendering. The component will have to handle rendering when it doesn't have the information yet.