Skip to content

Commit

Permalink
feat: ToastOptionAtom으로 position 관리할 수 있도록
Browse files Browse the repository at this point in the history
  • Loading branch information
Doeunnkimm committed Jan 11, 2024
1 parent 24c0916 commit 0f96833
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
18 changes: 10 additions & 8 deletions src/components/atoms/toast/Toast.atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,19 @@ interface ToastsProps {
sequence: number;
}

export interface ToastOptionProps {
position: string;
}

export const toastsAtom = atom<ToastsProps>({
toasts: [],
sequence: 0,
});

export const toastOptionAtom = atom<ToastOptionProps>({
position: 'bottom-[84px]',
});

export const removeToastAtom = atom(null, (get, set, id: number) => {
const prev = get(toastsAtom);
set(toastsAtom, {
Expand All @@ -24,15 +32,9 @@ export const toastAtom = atom(
(get) => get(toastsAtom).toasts,
(get, set, type: ToastProps['type']) => (title: string) => () => {
const prev = get(toastsAtom);
const newToast = { type, title, id: prev.sequence };
set(toastsAtom, {
toasts: [
{
type,
title,
id: prev.sequence,
},
...prev.toasts,
],
toasts: [...prev.toasts, newToast],
sequence: prev.sequence + 1,
});
},
Expand Down
7 changes: 3 additions & 4 deletions src/components/atoms/toast/ToastProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@ import * as Portal from '@radix-ui/react-portal';
import { useAtomValue } from 'jotai';

import { Toast } from './Toast';
import { toastsAtom } from './Toast.atom';

const TOAST_POSITION = 'bottom-[84px]';
import { toastOptionAtom, toastsAtom } from './Toast.atom';

export const ToastProvider = () => {
const { toasts } = useAtomValue(toastsAtom);
const { position } = useAtomValue(toastOptionAtom);

return (
<Portal.Root>
<div className={`fixed ${TOAST_POSITION} left-1/2 transform translate-x-[-50%]`}>
<div className={`fixed ${position} left-1/2 transform translate-x-[-50%]`}>
{toasts.map((toast) => (
<Toast key={toast.id} {...toast} />
))}
Expand Down
11 changes: 9 additions & 2 deletions src/hooks/useToast.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { useEffect } from 'react';
import { useSetAtom } from 'jotai';

import { toastAtom } from '@/components/atoms/toast/Toast.atom';
import type { ToastOptionProps } from '@/components/atoms/toast/Toast.atom';
import { toastAtom, toastOptionAtom } from '@/components/atoms/toast/Toast.atom';

export const useToast = () => {
export const useToast = (option?: ToastOptionProps) => {
const addToast = useSetAtom(toastAtom);
const setOption = useSetAtom(toastOptionAtom);

useEffect(() => {
if (option) setOption(option);
}, [option, setOption]);

return {
success: addToast('success'),
Expand Down

0 comments on commit 0f96833

Please sign in to comment.