-
-
Save brunosabot/d9f87875cab301f8d2708700666f27aa to your computer and use it in GitHub Desktop.
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
export const HelloApiContext = React.createContext({ values: { name: "" } }); | |
export function useQuery(url) { | |
const [error, setError] = useState(false); | |
const [loading, setLoading] = useState(true); | |
const [serverData, setServerData] = useState({ name: "" }); | |
const loadData = useCallback(() => { | |
setLoading(true); | |
setError(false); | |
fetch(url) | |
.then((result) => result.json()) | |
.then((data) => { | |
setServerData(data); | |
setLoading(false); | |
}) | |
.catch(() => setError(true)); | |
}, [url]); | |
return { error, loading, data: serverData, loadData }; | |
} | |
export function MyHelloApiComponent({ children }) { | |
const { error, loading, data, loadData } = useQuery( | |
"https://brunosabot.dev/api/hello/" | |
); | |
useEffect(loadData, []); | |
return ( | |
<HelloApiContext.Provider value={{ values: { error, loading, data } }}> | |
{children} | |
</HelloApiContext.Provider> | |
); | |
} | |
export function MyRenderingComponent() { | |
const { values } = useContext(HelloApiContext); | |
if (error) return <div>An error has occurred</div>; | |
if (loading) return <div>Loading</div>; | |
return <div>{values.data.name}</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment