# All files / src/hooks useToast.js

100% Statements 14/14
100% Branches 4/4
100% Functions 6/6
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35

    6x

    244x

    244x
    18x

    244x
    4x

    244x
    55x
    37x

    18x
    4x

    18x

    244x

     import { useCallback, useEffect, useState } from 'react';

    export const TOAST_DURATION = 3000;

    export function useToast(duration = TOAST_DURATION) {
      const [toast, setToast] = useState({ message: '', type: 'error' });

      const showToast = useCallback((message, type = 'error') => {
        setToast({ message, type });
      }, []);

      const clearToast = useCallback(() => {
        setToast({ message: '', type: 'error' });
      }, []);

      useEffect(() => {
        if (!toast.message) {
          return undefined;
        }

        const timeoutId = setTimeout(() => {
          clearToast();
        }, duration);

        return () => clearTimeout(timeoutId);
      }, [toast.message, duration, clearToast]);

      return {
        toastMessage: toast.message,
        toastType: toast.type,
        showToast,
        clearToast
      };
    }