diff --git a/_UseFetch.js b/_UseFetch.js new file mode 100644 index 0000000..9363f7d --- /dev/null +++ b/_UseFetch.js @@ -0,0 +1,24 @@ +import React from 'react'; + +const useFetch = (url, options) => { + + const [items, setItems] = React.useState([]); + const [error, setError] = React.useState(null); + + React.useEffect(() => { + const fetchItems = async () => { + try { + const res = await fetch(url, options); + const items = await res.json(); + setItems(items); + } catch (error) { + setError(error); + } + }; + fetchItems(); + }, [url, options]); + + return { items, error }; +} + +export default useFetch; diff --git a/index.js b/index.js index 3e5d97f..0d7d7c0 100644 --- a/index.js +++ b/index.js @@ -1,29 +1,25 @@ import React, { Component } from 'react'; import { render } from 'react-dom'; -import Hello from './Hello'; -import Title from './Title'; +import useFetch from './_UseFetch'; import './style.css'; -class App extends Component { - constructor() { - super(); - this.state = { - name: 'React', - title: 'My first stackblitz app' - }; - } +function MyComponent() { + const res = useFetch('https://jsonplaceholder.typicode.com/albums', {}); - render() { - return ( -
- Start editing to see some magic happen :) -
-Album: {id} user: {userId}
+title: {title}
+