Files
link-free/src/components/Dash/SaveChangesAlert/index.tsx
T

58 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-12-15 08:11:58 -03:00
import { useRouter } from 'next/router'
2021-12-19 20:03:59 -03:00
import { useData } from 'hooks/useData'
import { api } from 'services/api'
import { removeLocalStorageData } from 'utils/localStorage'
import { Button } from 'components/Button'
2021-12-15 08:11:58 -03:00
import { ButtonsGroup, Wrapper } from './styles'
2021-12-19 20:03:59 -03:00
import type { Data } from '../../../types/Data'
import type { Dispatch, SetStateAction } from 'react'
2021-12-15 08:11:58 -03:00
type SaveChangesAlertProps = {
hasUnsavedChanges: boolean
setHasUnsavedChanges: Dispatch<SetStateAction<boolean>>
initialData: Data
}
export function SaveChangesAlert({
hasUnsavedChanges,
setHasUnsavedChanges,
initialData
}: SaveChangesAlertProps) {
const { push } = useRouter()
const { data, setData } = useData()
const handleSave = async () => {
try {
await api.put('data', { data })
removeLocalStorageData()
setHasUnsavedChanges(false)
setData(data)
push('/')
} catch (error) {
console.error(error)
}
}
const handleCancel = () => {
setHasUnsavedChanges(false)
removeLocalStorageData()
setData(initialData)
}
2021-12-18 00:50:54 -03:00
return hasUnsavedChanges ? (
<Wrapper>
2021-12-15 08:11:58 -03:00
You have unsaved changes.
<ButtonsGroup>
2021-12-18 22:41:05 -03:00
<Button size="small" backgroundColor="transparent" onClick={() => handleCancel()}>
2021-12-15 08:11:58 -03:00
Cancel
</Button>
2021-12-18 00:50:54 -03:00
<Button size="small" onClick={() => handleSave()}>
2021-12-15 08:11:58 -03:00
Save
</Button>
</ButtonsGroup>
</Wrapper>
2021-12-18 00:50:54 -03:00
) : null
2021-12-15 08:11:58 -03:00
}