Fetching Data with fetch api for a React application

Rmag Breaking News

Suppose you need to fetch some data from a source say data.json for your react application

const getData = () => {
return (
fetch(‘data.json’).then((res)=>{
if (res.status == 200){
return res.json()

}else{
throw Error(‘Something went wrong’)

}

}).then((data) => {
console.log(data)
return data

})
.catch((error) => {
console.log(error)

}))

}

export default getData

Here .then((data) => {
console.log(data)
return data } part returns the data that we need. Now since then block automatically returns a promise so even if the data is returned explicitly it gets wrapped into a promise. So when we use this function to fetch data in our React app

useEffect(()=>{
if(!data)){
console.log(“Get the data”)
getData().then((data)=>{

setdata(data)
})

We need to resolve this promise . To resolve the promise we need another then block and then can be chained only in a function that return a promise. So, the getData function has to return the fetch api call which returns a promise .Finally now we can

getData().then((data)=>{

…do whatever is needed with the data
})

Leave a Reply

Your email address will not be published. Required fields are marked *