this is my code and print is a page
and getdata
is an async function that returns a promise
const print = () => { getdata.then((res)=>{ return (<p>{res}</p>) }) return( <> <div>{getdata()}</div> </> ) } export default print;
how can I print data on the page?
Advertisement
Answer
//Use a state to store fetched data const [data, setData] = useState(''); //useEffect to fecth data on first render useEffect(()=>{ //Self calling async function (async()=>{ let fetched = await getdata() let json = await fetched.json() setData(json) })() },[]) return( <> <div>{data}</div> </> )
And if data is an array of strings
//Use a state to store fetched data const [data, setData] = useState(''); //useEffect to fecth data on first render useEffect(()=>{ //Self calling async function (async()=>{ let fetched = await getdata() let json = await fetched.json() setData(json) })() },[]) return( <> <div>{data.map(elem => <p>{elem}</p>}</div> </> )