-
-
Save brunosabot/a48185e09bac40b2044a5f64ceb91642 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 MyHelloApiComponent({ children }) { | |
const [error, setError] = useState(false); | |
const [loading, setLoading] = useState(false); | |
const [serverData, setServerData] = useState({ name: "" }); | |
const loadData = useCallback(() => { | |
setLoading(true); | |
setError(false); | |
fetch("https://brunosabot.dev/api/hello/") | |
.then((result) => result.json()) | |
.then((data) => { | |
setServerData(data); | |
setLoading(false); | |
}) | |
.catch(() => setError(true)); | |
}, []); | |
useEffect(loadData, []); | |
return ( | |
<HelloApiContext.Provider | |
value={{ values: { error, loading, data: serverData } }} | |
> | |
{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