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(…
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()
}, [])