Skip to content

Instantly share code, notes, and snippets.

@EmmanuelDemey
Created October 24, 2023 08:00
Show Gist options
  • Save EmmanuelDemey/17ed32421ac1c7258bd611745d050950 to your computer and use it in GitHub Desktop.
Save EmmanuelDemey/17ed32421ac1c7258bd611745d050950 to your computer and use it in GitHub Desktop.
import "./App.css";
import { createContext, lazy, useContext, useEffect, useState } from "react";
const Excel = lazy(() => import("./Demo2"));
export const i18nContext = createContext("bouh");
export const I18nContextProvider = i18nContext.Provider;
export const useI18n = () => {
const context = useContext(i18nContext);
if (!context) {
throw new Error("Le Provider n'a pas été trouvé");
}
return context;
};
const useAsyncTask = (promiseFactory) => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState();
const [err, setErr] = useState();
useEffect(() => {
promiseFactory()
.then((d) => setData(d))
.then(() => setLoading(false))
.catch((e) => setErr(e));
}, []);
return {
loading,
data,
err,
};
};
function App() {
const { loading, data } = useAsyncTask(() =>
fetch("https://swapi.dev/api/people/1/").then((response) => response.json())
);
if (loading) {
return <p>Loading...</p>;
}
return <p>{data.name}</p>;
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment