Skip to content

Commit

Permalink
Improve use-async hook
Browse files Browse the repository at this point in the history
Use state to store data, removed use of ref

Fixes related to #112
  • Loading branch information
itsmemyk08 committed Jun 8, 2023
1 parent 27341f8 commit 496d72e
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions axelor-front/src/hooks/use-async/use-async.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DependencyList, useRef, useState } from "react";
import { DependencyList, useState } from "react";
import { useAsyncEffect } from "../use-async-effect";

export function useAsync<T>(
Expand All @@ -9,25 +9,25 @@ export function useAsync<T>(
data?: T;
error?: any;
} {
const [state, setState] = useState<"loading" | "hasData" | "hasError">();
const [error, setError] = useState<any>();
const dataRef = useRef<T>();
const [{ state, data, error }, setState] = useState<{
state?: "loading" | "hasData" | "hasError";
data?: T;
error?: any;
}>({});

useAsyncEffect(async () => {
setState("loading");
setState((draft) => ({ ...draft, state: "loading" }));
try {
const res = await func();
dataRef.current = res;
setState("hasData");
const data = await func();
setState({ state: "hasData", data });
} catch (e) {
setError(e);
setState("hasError");
setState((draft) => ({ ...draft, state: "hasError", error: e }));
}
}, deps);

return {
state: state ?? "loading",
data: dataRef.current,
data,
error,
};
}

0 comments on commit 496d72e

Please sign in to comment.