0

So I'm trying to render a function that is called when my UI renders and it gets the necessary information, The issue is that since this function needs to be an async function I'm unable to render html.

 async function getImages(path) {
        var x;
        try {
            const { data, error } = await supabase.storage.from('avatars').createSignedUrl(url, 60000000)
            if (error) {
                throw error
            }
            if (data) {
                x = data.signedURL
            }
         
        } catch (error) {
            console.log('Error downloading image: ', error.message)
        }
        finally {
            console.log(x)
        }
        return (<img src={x} className='w-14 h-14  rounded-full border border-bordergray' />)


    }

I call this function later in my render as usual like this - {getImages(imgurl)}

I get the following 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.
1
  • 1
    You can't use a Promise object as a React child, but you can use useEffect to run the async function, and use useState to handle the states of your 'x' (setState within your useEffect) Commented Jul 2, 2022 at 16:11

1 Answer 1

3

You'd actually want to completely seperate the fetch from the render:

function Component() {
    const [data, setData] = useState();

    //use effect to fetch on mount
    useEffect(() => {
        //fetch here, then store the result in the state
    }, [])

    if (data === undefined) return; //you can return some loader here

    return <img src={data} />
}

You might even want to create a custom hook if you need this at multiple places.

Edit: You can of course pass the image url in the props of the component. Thus you have one component used for every image dynamically. If you don't want this component to be rendered before it has access to a url, just render it conditionnally.

Sign up to request clarification or add additional context in comments.

3 Comments

The issue is this function needs to be called only when the imgUrlis provided to it, It dynamically and changes for every item that I'm rendering and I do not have access to this imgUrl before the page renders for every item.
You can pass imgUrl as a prop to the component.
That was a great idea, I tried that and got it to work, thank you for that and I really appreciate the support. Learned something really valuable.

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.