how to update array in react typescript

283 views Asked by At

I'm trying to update my state on the form submission but I got an error on TypeScritp I'm new at TS and I don't know how to fix it

enum ServiceTypeEnum {
  Replace = 'replace product',
  Fix = 'fix product',
}

interface IProductName {
  name: string
  serviceType: ServiceTypeEnum
}

const index: FC<Props> = ({ className, ...props }) => {
const [dataArray, setDataArray] = useState({})

const onSubmit: SubmitHandler<IProductName> = data => {
    console.log(data.serviceType)
    setDataArray(prev => [
      ...prev,
      {
        name: data.name,
        type1: data.serviceType[0],
        type2: data.serviceType[1],
        id: Date.now(),
      },
    ])
    console.log(dArray)

    if (data.serviceType.length !== 0 && data.name !== '') {
      console.log(data)
    } else {
      alert('choose name and at least one type')
    }
  }
}

here is my error TS2461: Type '{}' is not an array type

I'm also try

const [dataArray, setDataArray] = useState([])

but I got this error

TS2345: Argument of type '(prev: never[]) => { name: string; type1: string; type2: string; id: number; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'.Type '(prev: never[]) => { name: string; type1: string; type2: string; id: number; }[]' is not assignable to type '(prevState: never[]) => never[]'. Type '{ name: string; type1: string; type2: string; id: number; }[]' is not assignable to type 'never[]'. Type '{ name: string; type1: string; type2: string; id: number; }' is not assignable to type 'never'.

in JS there was no error but I don't know the typeScript format I searched but I found nothing

1

There are 1 answers

0
JacobS On

This line:

const [dataArray, setDataArray] = useState({})

Should probably initialized with an array, and typed:

const [dataArray, setDataArray] = useState([] as Array<YourDataType>)

Or:

const [dataArray, setDataArray] = useState<Array<YourDataType>>([])

The reason Typescript complains about the array when it's not explicitly typed is that Typescript does not know what type of array it is, so Typescript assumes the array is of type never[]/Array<never> - once you add a type to useState or the array itself Typescript will be able to understand it.