Issue
I use input type="file"
and instead of saving data in FileData
I use just plain object and created a type for it: Record<string, File>
. It works well, but when I try to create a validator with zod
– I don't get how to create the same type for it.
The usage:
import { object as zodObject, string, number } from 'zod';
import { useValidators } from '../some';
const useValidation = () => {
const { createResolver } = useValidators();
return {
resolver: createResolver(
zodObject({
name: string(),
price: number(),
files: ???,
})
),
};
};
The doc is quite excessive, but I could not find any example for my case: https://github.com/colinhacks/zod
The usage of input:
const App = () => {
const [files, setFiles] = useState<Record<string, File>>({});
return (
<input
type="file"
onChange={event => {
const files = event.target.files;
const newFiles: Record<string, File> = {};
const keys = Object.keys(files);
for(let i = 0; i < keys.length; i++) {
const file = newFiles[key];
newFiles[file.name] = file;
}
setFiles(newFiles);
}}
/>
)
}
Solution
My colleague has found the solution:
// useValidation file
import { object as zodObject, string, number, record, any } from 'zod';
import { useValidators } from '../some';
const useValidation = () => {
const { createResolver } = useValidators();
return {
resolver: createResolver(
zodObject({
name: string(),
price: number(),
files: record(any()).nullable(),
})
),
};
};
And in the file that uses object with file data we use it in this way:
// fileInput on `onRemove` action return `fileName: string` and my file object looks like this: { fileName: File }
const [files, setFiles] = useState<Record<string, File> | null>(null);
<FileInput
onChange={(fileName) => {
const updatedFiles = { ...files as Record<string, File> };
delete updatedFiles[fileName];
setFiles(updatedFiles);
}}
/>
Answered By - Samat Zhetibaev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.