/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 */ import { FunctionComponent, useCallback, useState } from 'react' import { CustomerLocationData, EMPTY_CUSTOMER_LOCATION } from '../../../models' import { Button, ColumnLayout, Form, FormField, FormSection, Inline, Input, Stack } from 'aws-northstar' import { useHistory, useParams } from 'react-router-dom' import { v4 as uuid } from 'uuid' import { useCustomerLocationContext } from '../../../contexts/CustomerLocationContext' import { appvars } from '../../../config' import { dayjsutc } from '../../../utils/dayjs' import { useImmer } from 'use-immer' import { Draft } from 'immer' export const Editor: FunctionComponent = () => { const history = useHistory() const { customerLocationId } = useParams<{ customerLocationId: string }>() const [{ items: customerLocationItems, isLoading }, { updateItem, createItem }] = useCustomerLocationContext() const editMode = !(customerLocationId === 'new' || customerLocationId === undefined) const [customerLocationData, updateCustomerLocationData] = useImmer(() => { if (editMode && customerLocationItems != null) { const sel = customerLocationItems.find((x) => x.Id === customerLocationId) if (sel != null) { return sel } } return { ...EMPTY_CUSTOMER_LOCATION, Id: uuid(), } }) const [formError, setFormError] = useState() const onSubmit = useCallback( async (event: React.FormEvent) => { event.preventDefault() if (customerLocationData == null) { throw new Error('CustomerLocationData is null') } try { if (editMode) { updateItem(customerLocationData, true) } else { await createItem(customerLocationData) } history.push(`/${appvars.URL.CUSTOMER_LOCATION}/${customerLocationData.Id}`) } catch (err) { setFormError(`Error while ${editMode ? 'updating' : 'saving new'} customer location object: ${err}`) } }, [customerLocationData, history, updateItem, createItem, setFormError, editMode], ) if (customerLocationData == null) { return null } return (
} > { updateCustomerLocationData((draft: Draft) => { draft.deliveryCode = e }) }} /> { updateCustomerLocationData((draft: Draft) => { draft.latitude = parseFloat(e) }) }} /> { updateCustomerLocationData((draft: Draft) => { draft.longitude = parseFloat(e) }) }} /> { updateCustomerLocationData((draft: Draft) => { draft.warehouseCode = e }) }} /> { updateCustomerLocationData((draft: Draft) => { draft.deliveryName = e }) }} /> { updateCustomerLocationData((draft: Draft) => { draft.address = e }) }} />
) }