C
C
cester2020-02-04 10:04:25
typescript
cester, 2020-02-04 10:04:25

Issue with types when using useState, typescript/react?

Good afternoon! Please help me understand and fix the error with typescript .
Problem with types when using a state.
With typescript this is the first project, so the solution is probably very simple)

There is a given code

type State = {
  files: [] | { name: string; type: string }[];
};
...
  const [files, setFiles] = useState<State[]>([]);

...
  const handleDrop = (acceptedFiles: { name: string; type: string }[]) => {
    const filesToSave = isMultiple
      ? [...files, ...acceptedFiles]
      : [acceptedFiles[0]];

   setFiles(filesToSave); // здесь ошибка \\\\\\
  };


Error text

Argument of type '(State | { name: string; type: string; })[]' is not assignable to parameter of type 'SetStateAction<State[]>'.   
Type '(State | { name: string; type: string; })[]' is not assignable to type 'State[]'.     
Type 'State | { name: string; type: string; }' is not assignable to type 'State'.       
Property 'uploadedFiles' is missing in type '{ name: string; type: string; }' but required in type 'State'.


I will be grateful for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-02-04
@cester

type AcceptedFile = {
  name: string;
  type: string;
};
...
  const [files, setFiles] = useState<AcceptedFile[]>([]);
...
  const handleDrop = (acceptedFiles: AcceptedFile[]) => {
   setFiles((currentFiles) => {
     return isMultiple
      ? [...currentFiles, ...acceptedFiles]
      : [acceptedFiles[0]];
   });
  };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question