Firebase download URL disappears with variable inside React.js render()

In a part of the html I return inside React render function. The “stories” (which retrieves values from state before render) contains js objects with attributes including “url” and others. When logging the entire object and other attributes individually, they appear on the console but the “url” attribute doesn’t. The url contains the firebase download url for an image and it exists outside of the render function when I fetch it to load it into state. But disappears after I get into render(). This is a snippet inside of the render().

     <div className="Storysubmain">
        {stories.map((story, idx) => {
          console.log(story);
          console.log(JSON.stringify(story));
          console.log(story.url);
          return (
            <div className="story" key={idx}>
              {story.image != null ?
                <div className="storyimagebox">
                  <a rel='noopener noreferrer' target='_blank' href={story.link}>
                    <img src={story.url} alt='Related view' />
                  </a>
                </div>
                : ""
              }
              <div className="storydetails">
                {story.khronos == null ?
                  "" : (
                    <span className="storykhronos">{story.khronos}</span>
                  )
                }
                <span className="storytitle">{story.title}</span>
                <p>{story.text}</p>
              </div>
            </div>
          )
        })}
      </div>
    </div>

Output in the console is as follows:

enter image description here

So, the object shows the “url” attribute as an object but not as a string. “url” is undefined when accessed individually. I don’t know what’s going on. And as a result I get an alternate view of the image. Thanks in advance.

Answer

Since the JSON.stringify doesn’t show the url that means that that value/property is added after you initially log the object, and Chrome’s console is just updating the logged object with the new property.

Most likely the url is loaded asynchronously from somewhere, but we can’t say where that is based on the code you shared. It doesn’t matter anyway, as the solution is the same no matter where it happens: when you set the url on a story in the stories object, you also need to update the stories object in the state of your app, so that React know that it needs to update the UI for that object.

Leave a Reply

Your email address will not be published. Required fields are marked *