Skip to content

Instantly share code, notes, and snippets.

@raurir
Last active May 14, 2024 15:47
Show Gist options
  • Save raurir/3812c09efaff2713c0ddba883f51f852 to your computer and use it in GitHub Desktop.
Save raurir/3812c09efaff2713c0ddba883f51f852 to your computer and use it in GitHub Desktop.
Hook problem
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>
);
};
@jacksontriffon
Copy link

Approach 1:

import { useEffect, useState } from "react";

// you can not modify this function:
const getAdvice = async () => {
    console.log("getAdvice");
    const url = "https://api.adviceslip.com/advice";

    try {
        const response = await fetch(url);
        const json = await response.json();
        return json.slip.advice;
    } catch (error) {
        console.log("error", error);
        return "";
    }
};

export const HookProblem = () => {
    const [advice, setAdvice] = useState("");

    const fetchAdvice = async () => {
        const newAdvice = await getAdvice();
        setAdvice(newAdvice);
    };

    useEffect(() => {
        fetchAdvice();
    }, []);

    return <div>{advice}</div>;
};

Approach 2:

import { useEffect, useState } from "react";

// you can not modify this function:
const useAdvice = () => {
	const [advice, setAdvice] = useState("");

	const fetchAdvice = async () => {
		console.log("getAdvice");
		const url = "https://api.adviceslip.com/advice";

		try {
			const response = await fetch(url);
			const json = await response.json();
			setAdvice(json.slip.advice);
		} catch (error) {
			console.log("error", error);
		}
	};

	useEffect(() => fetchAdvice(), []);

	return { advice, fetchAdvice };
};

export const HookProblem = () => {
	const { advice, fetchAdvice } = useAdvice();
	return (
		<>
			<div>{advice}</div>
			<button onClick={fetchAdvice}>Click to load!</button>
		</>
	);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment