1

My child component receives a Promise which is fullfilled, now I want to access the values of it like this :

return (
    <>
        <h1>{profile.Email}</h1>

    </>
  )

The resolve looks like this in the console console.log(profile)

Promise {<fulfilled>: {…}
[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
Email: "XXXXn@gmail.com"
Firma: "Dr"
Hausnummer: "1"
Land: "Deutschland"
LogoId: "Bildschirmfoto 2022-05-16 um 15.26.25.png"
Nachname: "BXXXX"
PLZ: "31840"
Stadt: "Hameln"
Strasse: "Gutsstr"
Telefon: "2121212121"
Titel: "Dr"
Typ: "XXXXX"
Vorname: "XXXX"
__typename: "Profil"

I want to access each of these values in the return(). How do I do that? I can access them before with

profile.then((values) => {
      email = values.Email
      console.log(email)
    })

which gives the correct value in the console, but I need the value in the return. Any one can point me in the right direction?

LogiBaer
  • 43
  • 3

2 Answers2

0

I suggest looking into Reacts state and effect hooks using useState and useEffect.

You could make the component async (not sure if this is bad practice, but I do it without issue), but I suggest just using useEffect and a then() method, setting the state upon resolve. For example:

import { useState, useEffect } from "react";

function myComponent() {
    const [profile, setProfile] = useState();
    
    useEffect(() => {
        <your async api call>.then((prof) => setProfile(prof));
    }, []);

    return (
        data 
            ? <h1>{JSON.stringify(profile.Email)}</h1>
            : <h1>Fetching Data...</h1>
    )
}

export default myComponent;
Vendetta
  • 2,078
  • 3
  • 13
  • 31
0

There are multiple methods to solve this, one way of it can be using a state to store the value when promis gets resolved. To do that you can use a loader while the response or the promise is resolved.

const { profile } = props; //I'm pretending that profile comes as props
// if profile comes from an api that you're calling in the component itself, then initialize to a value and then set it
const [profileData, setProfileData] = useState();

useEffect(() => {
  setProfileData(profile);
}, [profile])

return (
  profileData ? 
  <>{profileData.Email}</> :
  <>loading...</>
);

if this dosen't help you or what I'm suggesting is not what you are seeking, please do comment on this answer