this is my code and print is a page
and getdata
is an async function that returns a promise
JavaScript
x
13
13
1
const print = () => {
2
getdata.then((res)=>{
3
return (<p>{res}</p>)
4
})
5
6
return(
7
<>
8
<div>{getdata()}</div>
9
</>
10
)
11
}
12
export default print;
13
how can I print data on the page?
Advertisement
Answer
JavaScript
1
19
19
1
//Use a state to store fetched data
2
const [data, setData] = useState('');
3
4
//useEffect to fecth data on first render
5
useEffect(()=>{
6
//Self calling async function
7
(async()=>{
8
let fetched = await getdata()
9
let json = await fetched.json()
10
setData(json)
11
})()
12
},[])
13
14
return(
15
<>
16
<div>{data}</div>
17
</>
18
)
19
And if data is an array of strings
JavaScript
1
19
19
1
//Use a state to store fetched data
2
const [data, setData] = useState('');
3
4
//useEffect to fecth data on first render
5
useEffect(()=>{
6
//Self calling async function
7
(async()=>{
8
let fetched = await getdata()
9
let json = await fetched.json()
10
setData(json)
11
})()
12
},[])
13
14
return(
15
<>
16
<div>{data.map(elem => <p>{elem}</p>}</div>
17
</>
18
)
19