Hook useAsync de React
index.html
y script.js
ya se han proporcionado en la máquina virtual. En general, solo es necesario agregar código a script.js
y style.css
.
Este código crea un hook personalizado que maneja llamadas asincrónicas. Acepta una función manejadora, fn
, y devuelve un objeto que contiene las propiedades de state
(value
, error
y loading
) y una función asincrónica run
. La función run
ejecuta la devolución de llamada proporcionada, fn
, mientras usa dispatch
para actualizar state
según sea necesario.
const useAsync = (fn) => {
const initialState = { loading: false, error: null, value: null };
const stateReducer = (state, action) => {
switch (action.type) {
case "start":
return { loading: true, error: null, value: null };
case "finish":
return { loading: false, error: null, value: action.value };
case "error":
return { loading: false, error: action.error, value: null };
default:
return state;
}
};
const [state, dispatch] = React.useReducer(stateReducer, initialState);
const run = async (args = null) => {
try {
dispatch({ type: "start" });
const value = await fn(args);
dispatch({ type: "finish", value });
} catch (error) {
dispatch({ type: "error", error });
}
};
return { ...state, run };
};
const RandomImage = (props) => {
const imgFetch = useAsync((url) =>
fetch(url).then((response) => response.json())
);
return (
<div>
<button
onClick={() => imgFetch.run("https://dog.ceo/api/breeds/image/random")}
disabled={imgFetch.loading}
>
Cargar imagen
</button>
<br />
{imgFetch.loading && <div>Cargando...</div>}
{imgFetch.error && <div>Error {imgFetch.error}</div>}
{imgFetch.value && (
<img
src={imgFetch.value.message}
alt="avatar"
width={400}
height="auto"
/>
)}
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<RandomImage />);
Haga clic en 'Go Live' en la esquina inferior derecha para ejecutar el servicio web en el puerto 8080. Luego, puede actualizar la pestaña Web 8080 para previsualizar la página web.