mirror of
https://github.com/bendtherules/react-hooks-with-class.git
synced 2026-08-18 13:53:06 +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";
|
import "./App.css";
|
||||||
|
|
||||||
export default () => {
|
const useFetch = url => {
|
||||||
const [todos, setTodos] = useState([]);
|
const [data, setData] = useState(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
const toggleComplete = i =>
|
// Similar to componentDidMount and componentDidUpdate:
|
||||||
setTodos(
|
useEffect(async () => {
|
||||||
todos.map(
|
const response = await fetch(url);
|
||||||
(todo, k) =>
|
const data = await response.json();
|
||||||
k === i
|
const [item] = data.results;
|
||||||
? {
|
setData(item);
|
||||||
...todo,
|
setLoading(false);
|
||||||
complete: !todo.complete
|
}, []);
|
||||||
}
|
|
||||||
: todo
|
return { data, loading };
|
||||||
)
|
};
|
||||||
);
|
|
||||||
|
export default () => {
|
||||||
|
const [count, setCount] = useState(0);
|
||||||
|
const { data, loading } = useFetch("https://api.randomuser.me/");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="App">
|
<div>
|
||||||
<Form
|
<p>You clicked {count} times</p>
|
||||||
onSubmit={text => setTodos([{ text, complete: false }, ...todos])}
|
<button onClick={() => setCount(count + 1)}>Click me</button>
|
||||||
/>
|
{loading ? <div>...loading</div> : <div>{data.name.first}</div>}
|
||||||
<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>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user