How to set an array of Objects in useState using TypeScript
Asked Answered
C

3

9
 const res = {
      results: {
        documents: [
          {
            suggestion: 'tes1',
          },
          {
            suggestion: 'test2',
          },
          {
            suggestion: 'test3',
          },
          {
            suggestion: 'test4',
          },
        ],
      },
      meta: {
        request_id: '0e6aa4da',
      },
    };

I would like to set that "res" data into useState().

So I created inferface:

interface IResult {
  documents: [
    {
      suggestion: string;
    }
  ];
}

This is how look like my useState:

  const [querySuggestionResult, setQuerySuggestionResult] = useState<IResult[]>(
    []
  );

I want to set this json file (response form API) into the useState, so i tried

setQuerySuggestionResult([{documents: res.results.documents}]);

I tried like that as well

setGuerySuggestionResult(res.results.documents);

an error what ive got

Can someone explain to me how to set an array of Objects to useState please !!

Cistaceous answered 15/3, 2022 at 14:14 Comment(3)
It should just be setQuerySuggestionResult(res.results.documents);Tilla
just fix mistake sorry for thatCistaceous
I tried setGuerySuggestionResult(res.results.documents); but not workingCistaceous
M
8

I find the easiest way to be using an Array generic type (Array<T>):

interface Foo {
    id: string;
}

const [list, setList] = useState<Array<Foo>>([]);

You can also specify an array literal (T[]):

const [listAlt, setListAlt] = useState<Foo[]>([]);
// edit: another way using `readonly`
const [readonlyList, setReadonlyList] = useState<readonly Foo[]>([]);
const [otherReadonlyList, setOtherReadonlyList] = useState<ReadonlyArray<foo>>([]);

Note that to use readonly, using Array<...> will not work (i.e., readonly Array<Foo> will not work). You must use the readonly Foo[] notation or use ReadonlyArray<Foo>.

Mide answered 2/5, 2023 at 1:41 Comment(0)
J
0

Is it possible the interface definition is incorrect? Should it not be something like this?:

interface IResult {
  documents: {
      suggestion: string;
    }[];
}
Jael answered 15/3, 2022 at 14:54 Comment(0)
C
0

I did like that:

First updated interface:

type SuggestionType = { suggestion: string };
export interface IResult {
  documents: SuggestionType[];
}

Second updated useState:

const [querySuggestionResult, setQuerySuggestionResult] = useState<IResult>();

And at last I am able to setState like this:

setQuerySuggestionResult(res.result); 

Thank You! Like it shere it !

Cistaceous answered 16/3, 2022 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.