Fetch data in React using Hooks

When a JavaScript date has gone bad, “Don’t call me,I’ll call you. I promise!” — anonymous

About Promises

Promises in React

A little about UseEffect hook

Fetch using fetch

React.useEffect(() => {
fetch("/todoapp/todos.json")
.then(resp => resp.json())
.then(data => {
// handle on success
})
.catch(err => {
// handle on error
});
}, []);

Fetch using async/await

const [todos, setTodos] = React.useState([]);React.useEffect(() => {
let fetchTodos = async (state) => {
let resp = await fetch("/todoapp/todos.json");
let data = await resp.json();
setTodos(data.todos);
};
fetchTodos();
}, []);

Handle errors within async/await

const [todos, setTodos] = React.useState([]);React.useEffect(() => {
let fetchTodos = async (state) => {
try {
let resp = await fetch("/todoapp/todos.json");
let data = await resp.json();
setTodos(data.todos);
} catch(error) {
throw new Error(error)
}
};
fetchTodos();
}, []);

regeneratorRuntime is not defined?

npm i @babel/preset-env @babel/plugin-transform-runtime @babel/runtime --save-dev
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime"
]
}

About Me

Love to scribble about JavaScript and React JS. Been almost a decade with the tech. I feel i can be of some help to those looking forward on these buddies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store