return a string from a function in reactjs


I’m trying to return a string from a function
this is the function :

const getImage = (name) => {
    const imageRef = ref(storage, name);
    getDownloadURL(imageRef).then((url) => {
      return url;

But it returned undefined, although when I log it to the console it gives the value that I expect.
I thought about creating a state, but I can’t because I’m going to call this function several times and I don’t think I can make a state for each one of them.

I want to call the function so that it can fill the “`src“ in the code below :

{post.image && (
                <div className="">
                  <img src={getImage(post.image)} alt="test" />

but It won’t work.

any help is appreciated, Thanks.

>Solution :

getImage() executes an asynchronous operation which means you can’t pass the return value of the function directly into the component because the data is not immediately ready. You need to wait for it to resolve.

Here’s a proof of concept. For a good user experience, you’ll also need to show a placeholder or do something else to avoid layout shifts while the image is loading.

If you can’t get the image url server-side, you can still do this client-side:

  1. For simplicity, let’s first refactor the function:
const getImage = name => getDownloadURL(ref(storage, name));
  1. Now, let’s define a function component:
function PostImage({image, alt}) {
  const [imageSrc, setImageSrc] = useState();

  useEffect(() => {
    (async () => {
      setImageSrc(await getImage(image));
  }, [image]);

  return imageSrc ? <img src={imageSrc} alt={alt} /> : null;
  1. Finally, let’s reference it:
{post.image && (
  <div className="">
    <PostImage image={post.image} alt="test" />

Leave a ReplyCancel reply