DEV Community

Moumita Dhar
Moumita Dhar

Posted on

Fetching Data with fetch api for a React application

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
Enter fullscreen mode Exit fullscreen mode

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)
    })
Enter fullscreen mode Exit fullscreen mode

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
    })
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
erikgiovani profile image
Erik Giovani

Good way to keep a cleaner useEffect 👍.

Just a tip, you can use three inverted quotation marks and add the language next to it to do syntax highlighting, how in markdown.

The text:

Image description

The Result

getData().then((data) => {  
  ...do whatever is needed with the data
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
erikgiovani profile image
Erik Giovani • Edited

You can also use the prettier onlite formatter to format the code before sharing it, which makes it easier to read.

prettier.io/playground/

Welcome to the DEV Community 👋

Collapse
 
dhar3428 profile image
Moumita Dhar

Thank you for your suggestion. I will surely take note of it.