Issue
How can I set the correct type in useState so I can push image as File in array ?
Here is my useState:
const [colorsAndImages, setColorsAndImages] = useState([{ images: [], colors: '' }])
Here is where I'm trying to push the image but I'm getting an error:
const handleSetImage = (event: React.ChangeEvent<HTMLInputElement>, index: number) => {
const file = event.target.files;
const list = [...colorsAndImages]
list[index].images.push(file?.item(0)!)
setColorsAndImages(list)
};
The error is on ...(file?.item(0)!)
Argument of type 'File' is not assignable to parameter of type 'never'.
Solution
When using the useState
hook without an explicit generic, TypeScript will try to infer the type from the initial passed value.
Since your initial value includes an empty array (for images
), TypeScript is unable to determine the type of the values that will be in that array and so assigns it the type never
.
To fix this, explicitly specify the type of your state when you initialize it:
const [colorsAndImages, setColorsAndImages] = useState<{images: File[], colors: string}[]>([{ images: [], colors: '' }])
Answered By - CRice
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.