Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript fetch data with and without axios

I am learning typescript and I have problem to fetch data without axios.
I am able to fetch data with axios.
But if I am using just fetch(), I am getting error.

Expected 0 arguments, but got 1.ts(2554)

Fetching data with axios. Everything is working fine.

 const fetch = async () => {
    try {
       let res = await axios('/api/getNews')
       //console.log(res.data)  // ok
       setData(res.data)        // all good
    } catch (error) {
       console.log(error)
    }
   }

   
  useEffect(() => {
    fetch()
  }, [])

But when I am trying to fetch data withot axios, I am getting errors.
Can you please show me how to fetch data without axios?
I would like to fetch data with async and await method, NO WITH then(res…).then(…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


const fetch = async () => {
     try {
       const res = fetch('/api/getNews') // '/api/getNews' is underline-error
       console.log(res.data)             // err => Expected 0 arguments, but got 1.ts(2554)
     } catch (error) {                      
       console.log(error)
     }
   }

   
  useEffect(() => {
    fetch()

  }, [])

>Solution :

you are missing the await keyword before the fetch call, also, the fetch function returns a Promise, not the data directly, so you need to use the .json() method to extract the data from the response.

const fetchData = async () => {
  try {
    const response = await fetch('/api/getNews')
    const data = await response.json()
    console.log(data) // should log the data
  } catch (error) {
    console.log(error)
  }
}

useEffect(() => {
  fetchData()
}, [])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading