Last active
May 14, 2024 15:47
-
-
Save raurir/3812c09efaff2713c0ddba883f51f852 to your computer and use it in GitHub Desktop.
Hook problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
// you can not modify this function: | |
const getAdvice = () => { | |
console.log("getAdvice"); | |
const [advice, setAdvice] = useState(""); | |
useEffect(() => { | |
const url = "https://api.adviceslip.com/advice"; | |
const fetchData = async () => { | |
try { | |
const response = await fetch(url); | |
const json = await response.json(); | |
setAdvice(json.slip.advice); | |
} catch (error) { | |
console.log("error", error); | |
} | |
}; | |
fetchData(); | |
}, []); | |
return advice; | |
}; | |
export const HookProblem = () => { | |
const advice = getAdvice(); | |
return ( | |
<div> | |
{advice} | |
{ | |
// how to getAdvice on demand? ie: | |
} | |
<button onClick={() => getAdvice()}>Click to load!</button> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Approach 1:
Approach 2: