Advertisement
butbanksy

Untitled

Jan 18th, 2021
1,450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useEffect, useState } from "react"
  2. import axios from "axios"
  3.  
  4. export default function LifeCycleFunc() {
  5.  
  6.     const [color, setColor] = useState("Red");
  7.     const [count, setCount] = useState(0);
  8.     const [posts, setPosts] = useState([]);
  9.     const [isLoading, setLoading] = useState(true);
  10.  
  11.  
  12.     useEffect(
  13.         () => {
  14.             console.log("I've been called")
  15.             document.title = `I've been called ${count} times `;
  16.            setTimeout(() => {
  17.                setColor("Blue");
  18.            }, 2000);
  19.  
  20.            return {
  21.                //used for cleanup effect
  22.            }
  23.        }, [count])
  24.  
  25.    useEffect(() => {
  26.        axios.get("https://jsonplaceholder.typicode.com/posts")
  27.            .then(response => {
  28.                setPosts(response.data)
  29.                setLoading(false);
  30.            })
  31.            .catch(err => {
  32.                console.error(err)
  33.                setLoading(false);
  34.            })
  35.    }, []);
  36.  
  37.    const increment = () => setCount(count + 1);
  38.    return (
  39.        <>
  40.            <h1>My favorite color is {color}</h1>
  41.            <button onClick={increment}>The count is : {count}</button>
  42.            {isLoading ? (<h3>Loading...</h3>) : posts.map(post => (
  43.                <>
  44.                    <h4>{post.title}</h4>
  45.                    <p>{post.body}</p>
  46.                </>
  47.            ))}
  48.        </>
  49.    )
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement