Terry
Terry

Reputation: 1691

How to declare type of an array of a dynamic object as react state?

I need to declare an array of objects, but unlike the other answers on StackOverflow my object is dynamic at runtime.

Example,

Possible [{"id":"1", "random1": "1", "random1": "1", "random1": "1"}]

Possible [{"id":"2", "p": "p2", "p2": "o2"}]

I have data: {}[] but where do I put the any?

const [data, setData] = useState({ data: {}[], isFetching: false });

Or can I define this in a way where I can say there will always be an id: string index but the rest can be any.

Something like this, which is not valid, but perhaps something like this is?

const [data, setData] = useState({ data: { [index: string]: any }[];, isFetching: false });

Upvotes: 0

Views: 108

Answers (1)

leonardfactory
leonardfactory

Reputation: 3501

You can declare an auxiliary type, in order to specify your dynamic structure and keep your code clean:

type Data = {
  data: { [index: string]: any }[];
  isFetching: boolean;
}
// ...
useState<Data>({ data: [], isFetching: false });
// or
useState({ data: [], isFetching: false } as Data);

Given it is React, nothing stops you from having two states (but I suppose you don't like that given your actual code), like:

const [isFetching, setIsFetching] = useState(false);
const [data, setData] = useState([] as ({ [index: string]: any }[]));

Upvotes: 1

Related Questions