amosproj / amos2021ss02-project2-context-map

A context map for corporate data
MIT License
1 stars 0 forks source link

Asynchronous "manager" to retrigger load operations #106

Closed CatoLeanTruetschel closed 3 years ago

CatoLeanTruetschel commented 3 years ago

Find an OSS library or implement a functionality that allows not only an initial load operation but a retrigger of the load when an action occurs in the frontend (f.e. a button click).

joluj commented 3 years ago

RxJS/React-RxJS could be a solution. The you can listen on changes from multiple sources (e.g. on load, on button click, ...)

Example from the documentation with an on-click (your example) and timer (must be replaced, e.g. on-load):

import { merge, fromEvent, interval } from 'rxjs';

const clicks = fromEvent(document, 'click');
const timer = interval(1000);
const clicksOrTimer = merge(clicks, timer);

clicksOrTimer.subscribe(x => console.log(x)); // fires when timer or click event happens

I know this lib from developing with angular, so can help you with it.

joluj commented 3 years ago

Take a look at https://github.com/amosproj/amos-ss2021-project2-context-map/blob/ffc199d53af235c6338604b3da1ec0901e0a2606/frontend/src/search/Searchbar.tsx#L67-L73

searchInput$ fires when something is typed in the search input. In your case you would have to write it like that:

  useEffect(() => {
    const sub = merge(of(null), searchInput$.current).subscribe(...);

    return () => sub.unsubscribe();
  }, []);

of(null) fires instantly, so on the initial load (mount) operation. The query loadSearchResult() is also triggered manually after the reload.

It also prevents memory leaks by unsubscribing to all merged observables on unmount (-> return statement of the function in useEffect).