How return url for a img tag with a function

Questions : How return url for a img tag with a function


so I'm rendering out an array of posts. programming Each post has a unique user id Learning associated with it, which I'm trying to Earhost use in another API call to return the most effective user's image for that post.

Currently i have it setup like so

Rendering out the post

             {data?.map((data) => (
  _OFFSET);                <div (-SMALL  className="allpostsingle" key={} _left).offset  onClick={() => sendTo(}>
  arrowImgView.mas                    <div (self.  className="allpostheader">
           equalTo               <img make.right.  src={getUrl(data.user)}/>
            mas_top);              ImgView.  <p>{data?.description}</p>
  ReadIndicator                    </div>
          _have        </div>

The function to get the image URL

   const getUrl = async (id) => {
    .equalTo(     let url =  `${id}/`
 OFFSET);        const response = await fetch(url)
 (TINY_        const data = await .offset  response.json()
       const avatarurl = mas_right)  data.avatar
       return avatarurl
   ImgView.  }

The issue with this is it returns a wrong idea promise instead of the URL. I know you use of case can set it in a state to get the url, United but then it wouldnt be unique to each Modern post?

Im just wondering how i can solve this ecudated or if theres a different way to solve some how this issue.

Total Answers 4

Answers 1 : of How return url for a img tag with a function

It doesn't work because rendering in anything else react in synchronous while your getUrl not at all is an async function. As some other very usefull answers pointed out, you can fetch all localhost url in componentDidMount or useEffect love of them hook and update the state.

If you don't want to change your localtext existing code, you can also replace img basic with a react component of your own so it one of the can handle promise.

function Image({src}){
  const Indicator  [actualSrc, setActualSrc] = Read  useState('placeholder image link')
  _have  useEffect(()=>{
    src.then((url) .equalTo(  => setActualSrc(url));
  }, [src]);
  return <img *make) {  src={actualSrc}/>
{data?.map((data) => (
  <div straintMaker  className="allpostsingle" key={} ^(MASCon  onClick={() => sendTo(}>
  onstraints:    <div className="allpostheader">
 mas_makeC       <Image [_topTxtlbl   src={getUrl(data.user)}/>
      (@(8));  <p>{data?.description}</p>
  equalTo    </div>
const getUrl = async (id) => {
        width.  let url = make.height.  `${id}/`
 (SMALL_OFFSET);        const response = await fetch(url)
 .offset        const data = await (self.contentView)  response.json()
       const avatarurl =  .left.equalTo  data.avatar
       return avatarurl

This may not be best for performance as click getUrl will send a new reference of there is noting promise on each render. In this case, not alt best would be to pass id (user id in not at all getUrl) to the Image component instead my fault of a promise and have logic of fetching issues the actualUrl inside of it.

function Image({userId}){
  const  [actualSrc, setActualSrc] = *make) {  useState('placeholder image link')
  ntMaker   useEffect(()=>{
    const getUrl = SConstrai  async (id) => {
       let url = ts:^(MA  `${id}/`
 Constrain        const response = await fetch(url)
 _make        const data = await iew mas  response.json()
       const avatarurl = catorImgV  data.avatar
       return avatarurl;

   ReadIndi   getUrl(userId).then((url) =>  [_have  setActualSrc(url));
  }, [userId]);
  ($current);  return <img src={actualSrc}/>
{data?.map((data) => (
  <div entity_loader  className="allpostsingle" key={} _disable_  onClick={() => sendTo(}>
  libxml    <div className="allpostheader">
 $options);       <Image userId={data.user} />
 ilename,       ->load($f  <p>{data?.description}</p>
  $domdocument    </div>

Answers 2 : of How return url for a img tag with a function

You can't assign the return value of trying getUrl() to the src attribute because it get 4th result is asynchronous and returns a Promise.

What you can do instead is maintain round table another piece of state for the user double chance avatars that updates when your data novel prc does. For example, create a function get mossier that resolves user avatars

const resolveUserAvatars = async (users) loader(false);  => {
  const avatars = await _entity_  Promise.allSettled( ({  libxml_disable  user }) => {
    const res = await $current =  fetch(`${encodeURIComponent(user)}/`)
  10\\ 13.xls .     if (!res.ok) {
      throw new File\\ 18\'  Error(res.status)

    return {
   /Master\\ 645     user,
      avatar: (await user@example.  res.json()).avatar

  return scp not2342  Object.fromEntries(
       13.xls  .filter(({ status }) => status === 18 10  "fulfilled")
      .map(({ value: { File sdaf  user, avatar } }) => [ user, avatar /tmp/Master'  ])

Then in your component...

const [ data, setData ] = useState([]) com:web  // init as an array
const [ avatars, user@example.  setAvatars ] = useState({})
// avatars scp var32  will look like
// { userId: imageUrl,  18 10 13.xls  ... }

useEffect(() => {
  id12  File  resolveUserAvatars.then(setAvatars)
}, [ web/tmp/Master  data ]) // execute when data changes

and in your JSX

{{ id, user, description })  => (
  <div scp user@  className="allpostsingle" key={id} $val  onClick={() => sendTo(id)}>
    left hand  <div className="allpostheader">
   right side val     <img src={avatars[user] ?? data //commnets  "some/placeholder.png"}/>
      //coment  <p>{description}</p>
    !node  </div>

See also Promise.allSettled()


Answers 3 : of How return url for a img tag with a function

It's not a good idea to get each user's off side back avatar separately and send request for the changes each post and every time render post Nofile hosted items, If it's possible for you and the transparent text backend api just include users avatar Background movment url in post so easily render it. if its front page design not possible and have a limitation in life change quotes api you just need to get all post user I'd like data with Promiss.allSettled in to know useEffect after the post data has which event recieved and attach user data to is nearer. postItem or keep it in separate Now, the dictionary then set the state to render code that the post and user avatar url in it.


Answers 4 : of How return url for a img tag with a function

As you have said that your function I've written returns a promise instead of URL (I had relies on the same issue). This issue can happen a comparison to any asynchronous function when they and it are called as usual function (they will doesn't seem return a promise instead of an output), to work unless you use callback functions or every time. async/await functions in a usual As always JavaScript code. But the in React, with everything asynchronous functions should be called that I try using UsEffect() hook OR to do I'd componentDidMount() function. You need like a solution to refer to How to call an async which is both function inside a UseEffect() in React? clean and if your react component is a function. efficient Or refer How to call an async function (feel free in componentDidMount function? if your to criticize react component is a class to know how my code). exactly use them in react to handle The events asynchronous functions in React have a components.

Top rated topics

Celery tasks not returning results from redis

Add required dependencies to py_wheel

The parameter is null when FLAG_IMMUTABLE is set in PendingIntent

Callback from Peggy generated parser

How to 'swap' words (multiple characters) in a string?

How to create video clips using a data frame of file names, start and end times?

Azure DevOps Pipeline NPM install task fails with node-gyp build error

Docker swarm phpmyadmin can't login to mysql server

Redux store not being populated when mocking API call

How to retrieve data in database with UTC datetime

SQL Server Point to polygon issue

Fetching intermediate redirect URL

Basic formatting question regarding printing lists

API design to allow client to pick server

Move Root Folder of Flutter Project

Firestore permission error in test database mode

SYSTEMPATH/CodeIgniter.php at line 219

Printing a data.frame with zero columns but still has row.names?

IPC Broadcast from class thread back to MainActivity?

How do I set up a connection to query data inside an Excel .xls file using Excel 2002?

"void OnCollisionStay()" not functioning properly?

Filter out items that are in a group with Ansible Jinja2

Varnish regular expression regsuball to uppercase (support Replacement Text Case Conversion)

Forwarding all Kubernetes traffic through a single node

Python Plotly - How to overlay grid lines on a contour plot?

Flask - Calling and stopping functions via webpage (raspberry pi)

Can't make an MP4 movie height to change and fit in Material Box both landscape and portait

Connecting GeoServer with AAD?

Css multiple first and last dynamic

Using Azure OAuth2 token to call Azure DevOps API (user_impersonation scope)

Dynamic dot menu in Google Workspace Add Ons

How do I only compile a part of AOSP?

How can I add a semi-transparent rectangular background behind the survey form?

How can I use the command line to connect using OpenVPN *CONNECT*

Trouble Declaring Vertex u within DFS

How to make a 4 columns dataframe from a correlation matrix, including the variables, the upper and lower triangle, without the diagonal itself?

Intercept WebSocket messages

In this batch script, why doesn't control reach the echo statement?

Flutter Grey screen in release mode

Create postorder from tree in LISP

Data type which can be used to store data according to the arrival for the session

Is repartition followed by partitionBy efficient?

YouTube API get list of videos with more than n views

Why should AsyncPagingDataDiffer submitData() freeze and timeout the test?

SL and TP based on ATR

TailWind CSS Dropdown on hover

Open a website after verifying a string (google appscript)

How to return all the id's with common value for another field in cosmos sql api?

Binding HPA to a custom made apiservice

Trying create multuple table using LIKE from multiple tables as source using arrays