Skip to content

Commit

Permalink
Add memoization to useAwaitAction (#1)
Browse files Browse the repository at this point in the history
* Add memoization to useAwaitAction

* Remove type assertion

* Add test for memoized hook

* Add space to jsdoc comment
  • Loading branch information
FaBeyyy authored Aug 27, 2022
1 parent 264a532 commit 545b826
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
36 changes: 35 additions & 1 deletion src/useAwaitAction.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState } from 'react';
import { connect, DispatchProp, Provider } from 'react-redux';
import { act } from 'react-dom/test-utils';
import { render } from '@testing-library/react';
Expand Down Expand Up @@ -213,4 +213,38 @@ describe('useAwaitAction', () => {

console.error = errorHandler; // eslint-disable-line no-console
});

it('Should not re-initialize when storeAwait when component re-renders', async () => {
const renderCounter = jest.fn();

/**
* -
* @returns TestComponent
*/
const TestComponent = (): any => {
const storeAwait = useAwaitAction();
const [, triggerRender] = useState<null>();

useEffect(() => {
triggerRender(null);
});

useEffect(() => {
renderCounter();
}, [storeAwait]);

return null;
};

act(() => {
render(
<Provider store={store}>
<StoreAwaitProvider emitter={eventEmitter}>
<TestComponent />
</StoreAwaitProvider>
</Provider>,
);
});
expect(renderCounter).toHaveBeenCalledTimes(1);
});
});
9 changes: 7 additions & 2 deletions src/useAwaitAction.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMemo, useContext } from 'react';
import { Action } from 'redux';
import { useContext } from 'react';
import { useStore } from 'react-redux';
import { AwaitEventEmitterContext } from './context/awaitEventEmitterContext';
import { ActionTypes, createAwaitAction } from './createAwaitAction';
Expand All @@ -15,5 +15,10 @@ export function useAwaitAction<S extends Action = Action>(): (s: ActionTypes, e?

if (!eventEmitter) throw new Error('You need to access the await inside the <StoreAwaitProvider> component');

return createAwaitAction(store, eventEmitter);
const awaitAction: (s: ActionTypes, e?: ActionTypes | undefined) => Promise<S> = useMemo(
() => createAwaitAction(store, eventEmitter),
[store, eventEmitter],
);

return awaitAction;
}

0 comments on commit 545b826

Please sign in to comment.