TrainingMaterialCreateForm.tsx 3.76 KB
Newer Older
Stefan Probst's avatar
Stefan Probst committed
1
2
3
import { useRouter } from 'next/router'
import { useQueryClient } from 'react-query'
import type { TrainingMaterialCore, TrainingMaterialDto } from '@/api/sshoc'
4
import { useCreateTrainingMaterial } from '@/api/sshoc'
Stefan Probst's avatar
Stefan Probst committed
5
6
7
8
9
10
11
12
import type { ItemCategory } from '@/api/sshoc/types'
import { ActorsFormSection } from '@/components/item/ActorsFormSection/ActorsFormSection'
import { MainFormSection } from '@/components/item/MainFormSection/MainFormSection'
import { PropertiesFormSection } from '@/components/item/PropertiesFormSection/PropertiesFormSection'
import { RelatedItemsFormSection } from '@/components/item/RelatedItemsFormSection/RelatedItemsFormSection'
import { SourceFormSection } from '@/components/item/SourceFormSection/SourceFormSection'
import { Button } from '@/elements/Button/Button'
import { useToast } from '@/elements/Toast/useToast'
Stefan Probst's avatar
Stefan Probst committed
13
import { validate } from '@/lib/sshoc/validate'
Stefan Probst's avatar
Stefan Probst committed
14
15
import { useAuth } from '@/modules/auth/AuthContext'
import { Form } from '@/modules/form/Form'
16
import { getSingularItemCategoryLabel } from '@/utils/getSingularItemCategoryLabel'
Stefan Probst's avatar
Stefan Probst committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30

export type ItemFormValues = TrainingMaterialCore

export interface ItemFormProps<T> {
  category: ItemCategory
  initialValues?: Partial<T>
}

/**
 * Item edit form.
 */
export function ItemForm(props: ItemFormProps<ItemFormValues>): JSX.Element {
  const { category, initialValues } = props

31
  const categoryLabel = getSingularItemCategoryLabel(category)
Stefan Probst's avatar
Stefan Probst committed
32

Stefan Probst's avatar
Stefan Probst committed
33
34
35
36
37
38
39
40
  const useItemMutation = useCreateTrainingMaterial

  const toast = useToast()
  const router = useRouter()
  const auth = useAuth()
  const queryClient = useQueryClient()
  const create = useItemMutation({
    onSuccess(data: TrainingMaterialDto) {
41
      toast.success(`Successfully submitted ${categoryLabel}.`)
Stefan Probst's avatar
Stefan Probst committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55

      queryClient.invalidateQueries({
        queryKey: ['itemSearch'],
      })
      queryClient.invalidateQueries({
        queryKey: ['getTrainingMaterials'],
      })
      // queryClient.invalidateQueries({
      //   queryKey: ['getTrainingMaterial', { id: data.persistentId }],
      // })

      router.push({ pathname: `/${data.category}/${data.persistentId}` })
    },
    onError() {
56
      toast.error(`Failed to submit ${categoryLabel}.`)
Stefan Probst's avatar
Stefan Probst committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    },
  })

  function onSubmit(values: ItemFormValues) {
    if (auth.session?.accessToken == null) {
      toast.error('Authentication required.')
      return Promise.reject()
    }

    /**
     * Backend crashes with `source: {}`.
     */
    if (values.source && values.source.id === undefined) {
      delete values.source
    }

    return create.mutateAsync([{}, values, { token: auth.session.accessToken }])
  }

  function onValidate(values: Partial<ItemFormValues>) {
    const errors: Partial<Record<keyof typeof values, string>> = {}

Stefan Probst's avatar
Stefan Probst committed
79
    validate(values, errors)
Stefan Probst's avatar
Stefan Probst committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

    return errors
  }

  function onCancel() {
    router.push('/')
  }

  return (
    <Form
      onSubmit={onSubmit}
      validate={onValidate}
      initialValues={initialValues}
    >
      {({ handleSubmit, pristine, invalid, submitting }) => {
        return (
          <form
            onSubmit={handleSubmit}
            noValidate
            className="flex flex-col space-y-12"
          >
            <MainFormSection />
            <ActorsFormSection />
            <PropertiesFormSection />
            <RelatedItemsFormSection />
            <SourceFormSection />
            <div className="flex items-center justify-end space-x-6">
              <Button onPress={onCancel} variant="link">
                Cancel
              </Button>
              <Button
                type="submit"
                isDisabled={
                  pristine || invalid || submitting || create.isLoading
                }
              >
                Submit
              </Button>
            </div>
          </form>
        )
      }}
    </Form>
  )
}