I’m new to React and javascript and need some help. I’m using a function that returns a Promise including an interface. I want to access the variable in the Interface and apply it in <dl><dt>{//string variable}</dt></dl>
.
The problem is that I’m only getting a Promise object, and I need it as a string. How can I do this?
This is my async function for getting the Promise object and using it:
JavaScript
x
13
13
1
async function getName() {
2
const res = await getNamePromise(); // type: Promise<Interface>
3
console.log(res.name);
4
}
5
6
export function userInfo(){
7
return(
8
<dl>
9
<dd>{// need a string variable}</dd>
10
</dl>
11
);
12
}
13
When is write it like this:
getName().then((name) => console.log(name));
name is a string. But how can I store this as a string variable and use it?
Advertisement
Answer
You’re using React, so you should put api call and html tag into a react component, and save the api response data with component state to trigger re-render, try this:
JavaScript
1
34
34
1
function NameComponent() {
2
React.useEffect(() => {
3
async function getName() {
4
const res = await getNamePromise(); // type: Promise<Interface>
5
setName(res.name)
6
}
7
8
getName()
9
}, [])
10
11
React.useEffect(() => {
12
async function getPhoto() {
13
const res = await getPhotoPromise(); // type: Promise<Interface>
14
setPhoto(res.photo)
15
}
16
17
getPhoto()
18
}, [])
19
20
const [name, setName] = React.useState()
21
const [photo, setPhoto] = React.useState()
22
23
if (!name || !photo) {
24
return <div>Loading</div>
25
}
26
27
return(
28
<dl>
29
<dd>{name}</dd>
30
<dd>{photo}</dd>
31
</dl>
32
);
33
}
34