Skip to content

Commit

Permalink
Added delete entry to local state and UI
Browse files Browse the repository at this point in the history
  • Loading branch information
vinayh committed Mar 6, 2024
1 parent 5ae415d commit 2884c50
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 29 deletions.
64 changes: 40 additions & 24 deletions src/EntryForm.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import { Button, Group, Kbd, TagsInput, Text, TextInput } from "@mantine/core"
import { DateInput } from "@mantine/dates"
import { useForm } from "@mantine/form"
import "@mantine/dates/styles.css"

import { newLoading, updateError, updateSuccess } from "./notifications"
import { EntryFormData, ISODateZ, useUserStore } from "./user"
import { useUserStore } from "./user"
import { EntryInfo } from "./Calendar"

export const EntryForm = ({ entryInfo }: { entryInfo: EntryInfo }) => {
const { addUpdateEntry } = useUserStore()
const { addUpdateEntry, deleteEntry } = useUserStore()
const { date, entry } = entryInfo

const onSubmitEntryUpdate = (formEntry: EntryFormData) => {
const onSubmitEntryUpdate = (formEntry: {
note: string
tags: string[]
}) => {
form.validate()
const updateEntry = { ...formEntry, start: date }
const id = newLoading("Updating entry", "Please wait...")
addUpdateEntry(formEntry)
addUpdateEntry(updateEntry)
.then(() => {
console.log("Success received")
updateSuccess(id, "Entry updated", "Entry has been saved.")
})
.catch(error => {
Expand All @@ -25,17 +27,29 @@ export const EntryForm = ({ entryInfo }: { entryInfo: EntryInfo }) => {
})
}

const onDeleteEntry = () => {
const id = newLoading("Deleting entry", "Please wait...")
deleteEntry(date)
.then(() => {
updateSuccess(id, "Entry deleted", "Entry has been deleted.")
})
.catch(error => {
updateError(id, "Error", "Error deleting entry.")
console.error("Entry delete error: " + JSON.stringify(error))
})
}

const form = useForm({
initialValues: {
start: new Date(date),
// start: date,
note: entry && entry.note ? entry.note : "",
tags: entry && entry.tags ? entry.tags : [],
},
validate: {
start: value =>
value instanceof Date || ISODateZ.safeParse(value).success
? null
: "Invalid start date",
// start: value =>
// value instanceof Date || ISODateZ.safeParse(value).success
// ? null
// : "Invalid start date",
note: value => (value ? null : "Invalid note"),
// tags: value => (value !== undefined && value.length >= 1) ? null : "Invalid tags",
},
Expand All @@ -47,27 +61,18 @@ export const EntryForm = ({ entryInfo }: { entryInfo: EntryInfo }) => {
Date: {date}
</Text>
<form onSubmit={form.onSubmit(onSubmitEntryUpdate)}>
<DateInput
{/* <DateInput
withAsterisk
label="Start date"
placeholder="1 January 1984"
{...form.getInputProps("start")}
/>

/> */}
<TextInput
withAsterisk
label="Note"
placeholder=""
{...form.getInputProps("note")}
/>

{/* <TextInput
withAsterisk
label="Tags"
placeholder=""
{...form.getInputProps("tags")} /> */}
{/* TODO: Change tags entry to select list of available tags or add new tag */}

<TagsInput
label="Tags"
placeholder="Select tags"
Expand All @@ -77,10 +82,21 @@ export const EntryForm = ({ entryInfo }: { entryInfo: EntryInfo }) => {
Press <Kbd>↵ Enter</Kbd> to select a tag
</Text>

<Group justify="flex-end" mt="md">
<Button type="submit" radius="md" w={110}>
<Group justify="space-between" mt="md">
<Button type="submit" size="md" radius="md" w={110}>
Submit
</Button>
{entry ? (
<Button
radius="md"
size="xs"
variant="filled"
color="red"
onClick={() => onDeleteEntry()}
>
Delete
</Button>
) : null}
</Group>
</form>
</>
Expand Down
1 change: 0 additions & 1 deletion src/TextLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
Text,
} from "@mantine/core"

// type TextLoaderProps = Omit<LoaderProps, "children"> & { text: string }
type TextLoadingOverlayProps = Omit<LoadingOverlayProps, "loaderProps"> & {
text: string
}
Expand Down
55 changes: 51 additions & 4 deletions src/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ interface UserState {
updateProfile: (formData: ProfileFormData) => Promise<FetchStatus>
// updateContent: (entries: Entry[], tags: Tag[]) => Promise<FetchStatus>
addUpdateEntry: (formData: EntryFormData) => Promise<FetchStatus>
deleteEntry: (start: string) => Promise<FetchStatus>
setAuth: (auth: AuthUser | null) => void
shouldUpdateProfile: (auth: AuthUser) => boolean
isLoading: () => boolean
Expand Down Expand Up @@ -265,9 +266,7 @@ export const useUserStore = create<UserState>()(
)
}
const result = NewEntryZ.safeParse({
start: formatISO(formData.start, {
representation: "date",
}),
start: formData.start,
note: formData.note,
tags: formData.tags,
})
Expand Down Expand Up @@ -323,6 +322,54 @@ export const useUserStore = create<UserState>()(
return Promise.reject(FetchStatus.Error)
})
},
deleteEntry: async start => {
const userAuth = get().userAuth
if (
!userAuth ||
!get().userProfile ||
get().authStatus !== AuthStatus.SignedIn
) {
throw new Error(
"Invalid user session for adding/updating entry"
)
}
const result = ISODateZ.safeParse(start)
if (!result.success) {
console.error("Invalid start date for deletion: " + start)
return Promise.reject(FetchStatus.Error)
}
return userAuth
.getIdToken()
.then(idToken =>
fetch(
`${BACKEND_URL}/deleteEntry?uid=${userAuth.uid}&idToken=${idToken}&start=${result.data}`
)
)
.then(res => {
if (!res.ok) {
throw new Error("Server error when deleting entry")
}
return res.json()
})
.then(res => {
const start = ISODateZ.parse(res.start)
const entries = get().entries
if (!entries) {
console.error("No valid entries to update")
return Promise.reject(FetchStatus.Error)
}
delete entries[start]
get().setEntries(entries)
console.log(`Deleted entry with start date: ${start}`)
return Promise.resolve(FetchStatus.Success)
})
.catch(error => {
console.error(
`Error while deleting entry with start ${start}: ${error.message}`
)
return Promise.reject(FetchStatus.Error)
})
},
setAuth: (auth: AuthUser | null) => {
if (!auth) {
set(() => ({
Expand Down Expand Up @@ -534,7 +581,7 @@ export type ProfileFormData = {
}

export type EntryFormData = {
start: Date
start: string
note: string
tags: string[]
}

0 comments on commit 2884c50

Please sign in to comment.