aboutsummaryrefslogtreecommitdiffstats
path: root/hooks/usePopup.js
blob: 615d40396f271edf3fa109e0d0607b19e5f7b9b5 (plain) (blame)
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
36
37
38
39
import React, { createContext, useState, useContext } from 'react'
import Queue from 'helpers/queue'

const PopupContext = createContext()

export const PopupProvider = ({children}) => {
  const [popupData, setPopupData] = useState()

  const setPopup = p => {
    Queue.enqueue(
      () =>
        new Promise(r => {
          if (p.time) {
            setPopupData(p)
            setTimeout(() => {
              r(setPopupData());
            }, p.time);
          } else {
            setPopupData({
              ...p,
              ...(p.yes && {yes: {label: p.yes.label, action: () => p.yes.action().then(() => r(setPopupData()))}}),
              ...(p.no && {no: {label: p.no.label, action: () => p.no.action().then(() => {r(setPopupData())})}}),
            })
          }
        })
    );

  }

   return (
     <PopupContext.Provider value={{popupData, setPopup}}>
       {children}
     </PopupContext.Provider>
    )
}

const usePopup = () => useContext(PopupContext)

export default usePopup