简体   繁体   中英

React component renders before I can set src of image

I have this application that flashes a series of cards. Some have questions with text. No problem there obviously. But the image source is being retrieved from firebase. On each render I check if it has a question with text, or with an image and if it has an image I query the database for the downloadURL and insert that as the source. If I insert it hard coded it works fine, if I console log the response it's accurate. My problem is I believe that the component renders before I can insert the source dynamically. Code is below. And yes, I know with that many conditionals it looks like a christmas tree and is probably really bad practice. To save some reading I'll splice it where I make the request here...

useEffect(() => {
    if ("imageHolder" in active) {
      const asyncFunc = async () => {
        setLoading(true);
        setImage(true);
        await storageRef
          .child(active.imageHolder)
          .getDownloadURL()
          .then(function (url) {
            imageSrc = url;
            console.log("url returns ", url);
          })
          .catch(function (error) {
            console.log(error);
          });
      };
      asyncFunc();
      setLoading(false);
    }
  }, [active, getQuestions, correctAnswer]);

And where I insert it here

 ) : image ? (
          loading ? (
            <h1>Loading</h1>
          ) : (
            <img alt="" src={imageSrc} className="d-inline-block align-top" />
          )
        ) : (
          <h3>{active.question}</h3>
        )}
      </div>
      <div className="answerGrid">
        {loading ? (

Thanks for any advice at all. And stay healthy!

I think simple decision to this will be adding a logical "or" operator in src like this

<img alt="" src={imageSrc || ''} className="d-inline-block align-top" />

It might be helpful to see the rest of the code, but given the provided snippets, I'm assuming the problem is with how the imageSrc variable is getting set.

Have you tried managing the imageSrc as state? Eg

const [imageSrc, setImageSrc] = useState('')

// then use setImageSrc after getting the url
await storageRef
          .child(active.imageHolder)
          .getDownloadURL()
          .then(function (url) {
            setImageSrc(url)
            console.log("url returns ", url);
          })


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM