datamonkey
datamonkey

Reputation: 43

Rendering a returned value from an async function in ReactJS

I am trying to fetch a variable (avatar seed) from a database doing the following function:

async function getProfileData() {
    let response = await post('/getProfileData', {
        name: 'test'
    })

    return response
}

That works completely fine, the problem is that I need this seed to render in an element, but I am not sure how I would do that without the promise returns pending.

This is the element I am trying to add the seed to:

function Example() {
 return (
  <img src={`https://avatars.dicebear.com/api/croodles/${seed}.svg`} alt="Sprite"/>
 )
}

export default Example;

Upvotes: 0

Views: 123

Answers (1)

windmaomao
windmaomao

Reputation: 7680

There's lots of ways of doing that. I'm showing a basic one.

  function Example() {
    const [seed, setSeed] = useState(null)
    useEffect(() => {
      const s = await getProfileData()
      setSeed(s)
    }, [])

    if (!seed) return null
   
    return <img src={...} />
  }

Here if there's no seed, it'll display nothing instead of a picture.

Upvotes: 1

Related Questions