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) => {
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
console.log(data)
return data }
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
})
Top comments (3)
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:
The Result
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 👋
Thank you for your suggestion. I will surely take note of it.