2

How do I create a state array with react hooks? I am passing a Type I used this method but it's showing me lint error. I also want to know it's the correct method

const [myList, setList] = React.useState<IList[]>([
  {
    ID: 1,
    Lname: "R1",
    LType: 1
  },
  {
    ID: 2,
    Lname: "R4",
    LType: 5
  }
]);

And my type looks like

interface IList {
  ID: number;
  Lname: string;
  LType: number;
}
1
  • Please add the lint error text! Commented Nov 16, 2019 at 16:12

2 Answers 2

2

You just need to tell it it's an array of objects. Here's a codesandbox example of this typing working now.

const [myList, setList] = React.useState<IList[]>([
        {
            ID: 1,
            Lname: "R1",
            LType: 1
        }, {
            ID: 2,
            Lname: "R4",
            LType: 5
        }])
Sign up to request clarification or add additional context in comments.

5 Comments

I passed like that only. i forget to mention. still its showing lint
Argument of type '({ ID: number; Lname: string; LType: number; } | { ID: number; Lname: string; LType: number; })[]' is not assignable to parameter of type 'IList | (() => IList)'.
At this point, I suspect the issue is actually where you're using setList somewhere else in the app.
Here's an example of that typing working just fine codesandbox.io/s/cool-galois-j8lvw
I tried by changing the name. But still its showing the same. And @Nick you great, with give an example. thank you.
1

It looks like you're passing in the wrong type for state. Instead of IList, it looks like it should be IList[]

If you're still seeing errors, it might be useful to share them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.