Browse Source

Debounce margin calculation

We wait for at least 500ms before actually calculating the margin.
This avoids unnecessary API requests when the user rapidly edits
the input field.
debug-collab-settlement
Thomas Eizinger 3 years ago
parent
commit
b840bdee89
No known key found for this signature in database GPG Key ID: 651AC83A6C6C8B96
  1. 16
      taker-frontend/src/App.tsx
  2. 11
      taker-frontend/src/useDebouncedEffect.ts

16
taker-frontend/src/App.tsx

@ -11,7 +11,7 @@ import {
VStack,
} from "@chakra-ui/react";
import * as React from "react";
import { useEffect, useState } from "react";
import { useState } from "react";
import { Route, Routes } from "react-router-dom";
import { useEventSource } from "react-sse-hooks";
import useWebSocket from "react-use-websocket";
@ -33,6 +33,7 @@ import {
StateGroupKey,
WalletInfo,
} from "./types";
import useDebouncedEffect from "./useDebouncedEffect";
import useLatestEvent from "./useLatestEvent";
import usePostRequest from "./usePostRequest";
@ -81,7 +82,8 @@ export const App = () => {
);
let [makeNewOrderRequest, isCreatingNewOrderRequest] = usePostRequest<CfdOrderRequestPayload>("/api/cfd/order");
useEffect(() => {
useDebouncedEffect(
() => {
if (!order) {
return;
}
@ -91,12 +93,12 @@ export const App = () => {
price: order.price,
quantity,
};
calculateMargin(payload);
}, // Eslint demands us to include `calculateMargin` in the list of dependencies.
// We don't want that as we will end up in an endless loop. It is safe to ignore `calculateMargin` because
// nothing in `calculateMargin` depends on outside values, i.e. is guaranteed to be stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
[margin, effectiveQuantity, order]);
},
[margin, effectiveQuantity, order],
500,
);
const format = (val: any) => `$` + val;
const parse = (val: any) => val.replace(/^\$/, "");

11
taker-frontend/src/useDebouncedEffect.ts

@ -0,0 +1,11 @@
import { useEffect } from "react";
// Copied from: https://stackoverflow.com/a/61127960/2489334
export default function useDebouncedEffect(effect: () => void, deps: any[] | undefined, delay: number) {
return useEffect(() => {
const handler = setTimeout(() => effect(), delay);
return () => clearTimeout(handler);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...deps || [], delay]);
}
Loading…
Cancel
Save