Home > Mobile >  Converting class based js useState array to typescript Hook problem
Converting class based js useState array to typescript Hook problem

Time:12-02


UPDATE

I got this working by changing my useState declaration from:

const [ data, setData ] = useState([]);

to

const [ data, setData ] = useState<any>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}

However, I realise this just defeats the object of using Typescript. So, my next move based on @tomleb3 answer was to create an interface for data like so:

const [ data, setData ] = useState<DataType>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}
  
  interface DataType{
    chx: any,
    bin: string,
    type: string,
    ascii: string
  }

but this gives an error:

Argument of type 'never[]' is not assignable to parameter of type 'DataType | (() => DataType)'. Type 'never[]' is not assignable to type '() => DataType'. Type 'never[]' provides no match for the signature '(): DataType'.

I don't know how to progress from here as removing the [] useState declaration then pushes the error down to wherever I use a setData() call with the following error:

Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<DataType | undefined>'. Type 'any[]' is not assignable to type '(prevState: DataType | undefined) => DataType | undefined'.


ORIGINAL POST

I've been working with react / typescript for a few days and am teaching myself by doing a small project. As part of that I am currently converting some class based code into hooks.

I have the following (js) class based code that I don't know how to convert to use in a hook with typescript:

this.setState({
  data: [
    ...this.state.data,
    {
      chx: chx,
      type: type,
      bin: bin,
      ascii: ascii,
    },
  ],
});

In my hook based equivalent I know that I would use setData(); for a simple state. But, how do I convert the example above? My attempt (below) is clearly wrong, as I'm getting the error: Type '{ chx: unknown; type: string; bin: string; ascii: string; }' is not assignable to type 'never'. But I'm stuck for what I should do next to try and resolve this:

setData([
  ...data,
  {
    chx: chx,
    type: type,
    bin: bin,
    ascii: ascii,
  }
])

Any pointers / solutions would be greatly appreciated.

Thanks.

CodePudding user response:

The error you are receiving is a Typescript error, not a React error.
Your code is perfectly fine, but when working with Typescript we need to type our states just as well as everything else.

Which can look like this for example:

interface State {
   key1: string,
   key2: number,
   key3: boolean,
}

function myComponent() {
   const [state, setState] = useState<State>({
      key1: 'test',
      key2: 42,
      key3: false,
   })
}

This allows Typescript to know the structure of your state and thus enabling it to apply the relevant type guards and restrictions.

  • Related