1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00
claudiaHash 90f841bb13
No error shown for invalid file url (#1221)
* check file url

* logic fix

* display error message

* use x mark sign

* change border and background color for wrong input

* invalid input red border

* make error visible only for touched field

Co-authored-by: ClaudiaHolhos <claudia@oceanprotocol.com>
2022-03-29 15:14:46 +01:00

83 lines
2.5 KiB
TypeScript

import React, { ReactElement, useCallback, useEffect, useState } from 'react'
import { useField, useFormikContext } from 'formik'
import { toast } from 'react-toastify'
import FileInfo from './Info'
import UrlInput from '../URLInput'
import { InputProps } from '@shared/FormInput'
import { initialValues } from 'src/components/Publish/_constants'
import { getFileUrlInfo } from '@utils/provider'
import { FormPublishData } from 'src/components/Publish/_types'
export default function FilesInput(props: InputProps): ReactElement {
const [field, meta, helpers] = useField(props.name)
const [isInvalidUrl, setIsInvalidUrl] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const { values } = useFormikContext<FormPublishData>()
const loadFileInfo = useCallback(
(url: string) => {
const providerUri =
(values.services && values.services[0].providerUrl.url) ||
'https://provider.mainnet.oceanprotocol.com'
async function validateUrl() {
try {
setIsLoading(true)
const checkedFile = await getFileUrlInfo(url, providerUri)
setIsInvalidUrl(!checkedFile[0].valid)
checkedFile && helpers.setValue([{ url, ...checkedFile[0] }])
} catch (error) {
toast.error(
'Could not fetch file info. Please check URL and try again'
)
console.error(error.message)
} finally {
setIsLoading(false)
}
}
validateUrl()
},
[helpers, values.services]
)
useEffect(() => {
// try load from initial values, kinda hacky but it works
if (
props.value &&
props.value.length > 0 &&
typeof props.value[0] === 'string'
) {
loadFileInfo(props.value[0].toString())
}
}, [loadFileInfo, props])
async function handleButtonClick(e: React.SyntheticEvent, url: string) {
// File example 'https://oceanprotocol.com/tech-whitepaper.pdf'
e.preventDefault()
loadFileInfo(url)
}
function handleClose() {
helpers.setValue(initialValues.services[0].files)
helpers.setTouched(false)
}
return (
<>
{field.value[0].valid !== undefined ? (
<FileInfo file={field.value[0]} handleClose={handleClose} />
) : (
<UrlInput
submitText="Validate"
{...props}
name={`${field.name}[0].url`}
hasError={Boolean(meta.touched && isInvalidUrl)}
isLoading={isLoading}
handleButtonClick={handleButtonClick}
/>
)}
</>
)
}