mirror of
https://github.com/bendtherules/react-hooks-with-class.git
synced 2026-08-18 22:03:11 +00:00
fetch data from an api with useEffect
This commit is contained in:
+23
-34
@@ -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 (
|
||||
<div className="App">
|
||||
<Form
|
||||
onSubmit={text => setTodos([{ text, complete: false }, ...todos])}
|
||||
/>
|
||||
<div>
|
||||
{todos.map(({ text, complete }, i) => (
|
||||
<div
|
||||
key={text}
|
||||
onClick={() => toggleComplete(i)}
|
||||
style={{
|
||||
textDecoration: complete ? "line-through" : ""
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button onClick={() => setTodos([])}>reset</button>
|
||||
<div>
|
||||
<p>You clicked {count} times</p>
|
||||
<button onClick={() => setCount(count + 1)}>Click me</button>
|
||||
{loading ? <div>...loading</div> : <div>{data.name.first}</div>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user