Skip to content

Commit

Permalink
fix(Toaster): code breaks when toaster is in a useEffect
Browse files Browse the repository at this point in the history
related rsuite#2336
  • Loading branch information
maxpou committed Feb 15, 2022
1 parent 3b6c25c commit 38dff8f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 15 additions & 2 deletions src/toaster/test/toasterSpec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { screen } from '@testing-library/react';
import React, { useEffect } from 'react';
import { screen, render } from '@testing-library/react';
import toaster from '../toaster';

const element = document.createElement('div');
Expand Down Expand Up @@ -83,4 +83,17 @@ describe('toaster', () => {
clock.tick(400);
expect(screen.queryByTestId('message')).not.to.exist;
});

it('Should not throw errors when push() is called via useEffect', () => {
function MyComponent() {
useEffect(() => {
toaster.push(<div>Hi toaster!</div>);
}, []);

return <div>My component</div>;
}

expect(() => render(<MyComponent />)).not.to.throw();
expect(screen.getByText('Hi toaster!')).to.exist;
});
});
8 changes: 4 additions & 4 deletions src/toaster/toaster.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface Toaster {
* @param message
* @param options
*/
push(message: React.ReactNode, options?: ToastContainerProps): string;
push(message: React.ReactNode, options?: ToastContainerProps): string | undefined;

/**
* Remove a message by key
Expand Down Expand Up @@ -56,15 +56,15 @@ toaster.push = (message: React.ReactNode, options: ToastContainerProps = {}) =>
if (!container) {
container = createContainer(options.placement ?? '', options);
}
return container.current!.push(message);
return container.current?.push(message);
};

toaster.remove = (key: string) => {
containers.forEach(c => c.current!.remove(key));
containers.forEach(c => c.current?.remove(key));
};

toaster.clear = () => {
containers.forEach(c => c.current!.clear());
containers.forEach(c => c.current?.clear());
};

export default toaster;

0 comments on commit 38dff8f

Please sign in to comment.