bear
bear

Reputation: 11605

Objects are not valid as a React child (found: [object Promise]). But I am not returning a promise?

I'm trying to separate my components out so that I don't fetch data in a render function call.

So far, I've two functional components:

const Comment = ({data}) => (
    <React.Fragment>
        {data.map((comment, i) => (<li id={comment.id}>{comment.user.displayName}:{comment.text}</li>))}
    </React.Fragment>
);

const IssueComment = ({comment}) => {
    const [data, updateData] = useState();
    useEffect(() => {
        const getData = async () => {
            const resp = await user.getUser(comment.createdByUserId)
                .catch(e => console.log(e));
            const json = resp.json()
            comment.user = json
            updateData(json);
        }
        getData();
    }, []);

    return data && <Comment data={data} />
}

When I run the React build, the page render fails with the above error message. I thought that I was containing the async stuff to useEffect? What am I doing wrong?

Upvotes: 0

Views: 49

Answers (1)

Nikita Chayka
Nikita Chayka

Reputation: 2137

Your problem is in this line:

return data && <Comment data={data} />

Conditional rendering works fine with boolean variables (or conditions), not with others, say for example

return 0 && <Comment data={data}/>

It will render 0, not nothing.

You need some check on your data, like:

return data==null && <Comment data={data} />

And as @5ar mentioned in comment to you, .json() is a promise, so you need to await that too, but still above is valid - that was the main reason why you had that error in first place

Upvotes: 1

Related Questions