From ad2d4e9b362f2ee75b8972b07fbb594502f8c109 Mon Sep 17 00:00:00 2001 From: Ben Awad Date: Sat, 27 Oct 2018 20:11:20 -0500 Subject: [PATCH] fetch data from an api with useEffect --- src/App.js | 57 ++++++++++++++++++++++-------------------------------- 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/src/App.js b/src/App.js index 88164e7..3184caa 100644 --- a/src/App.js +++ b/src/App.js @@ -1,43 +1,32 @@ -import React, { useState } from "react"; +import React, { useState, useEffect } from "react"; -import Form from "./Form"; import "./App.css"; -export default () => { - const [todos, setTodos] = useState([]); +const useFetch = url => { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); - const toggleComplete = i => - setTodos( - todos.map( - (todo, k) => - k === i - ? { - ...todo, - complete: !todo.complete - } - : todo - ) - ); + // Similar to componentDidMount and componentDidUpdate: + useEffect(async () => { + const response = await fetch(url); + const data = await response.json(); + const [item] = data.results; + setData(item); + setLoading(false); + }, []); + + return { data, loading }; +}; + +export default () => { + const [count, setCount] = useState(0); + const { data, loading } = useFetch("https://api.randomuser.me/"); return ( -
-
setTodos([{ text, complete: false }, ...todos])} - /> -
- {todos.map(({ text, complete }, i) => ( -
toggleComplete(i)} - style={{ - textDecoration: complete ? "line-through" : "" - }} - > - {text} -
- ))} -
- +
+

You clicked {count} times

+ + {loading ?
...loading
:
{data.name.first}
}
); };