Home > Software engineering >  How to print async data in react
How to print async data in react

Time:07-25

this is my code and print is a page and getdata is a 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 in page

CodePudding user response:

//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>
  </>
)
  • Related