0

How can I set type to useState and render list with map in React TypeScript?

I have a component:

export type Item = {
  name: string;
  title: string;
};
export type ItemTypes = {
  item: Item[];
};

export const ItemList: FC = () => {
   const [items, setItems] = useState<ItemsTypes | []>([])

   useEffect(() => {
    let items = [
      {
        name: "A",
        title: "B",
      },
      {
        name: "C",
        title: "D",
      }
    ]
    setItems()
   }, [);

   return (
     <div>
         {items?.map((item) => (
          <>{item.name}</>
         ))}
     </div>
   )
}

And under .map line red stroke and saying:

any
Property 'map' does not exist on type 'ItemTypes | []'. 

Where is my mistake?

2 Answers 2

4

As defined ItemTypes is not an array but instead an object having property item, hence the error. Use Item[] instead.

const [items, setItems] = useState<Item[]>([])
Sign up to request clarification or add additional context in comments.

1 Comment

yes it's worked but useState<Item[]>(null) here need to be useState<Item[]>([])
0

There are a couple of things wrong with the your implementation.

First if you want to export the type alias ItemTypes you can set the type alias for ItemTypes like this export type ItemTypes = Item[].

Second, you are never calling setItems with the items you have created in useEffect.

Lastly, because you are trying to access the name property on each item you should be checking item.length in a conditional otherwise it will throw an error cannot access property name of undefined if you do try to load the items asynchronously.

Solution


    export type Item = {
      name: string;
      title: string;
    };

    export type ItemTypes = Item[];

    export const ItemList: FC = () => {
       const [items, setItems] = useState<ItemsTypes | []>([])

       useEffect(() => {
        let items = [
          {
            name: "A",
            title: "B",
          },
          {
            name: "C",
            title: "D",
          }
        ]
        setItems(items)
       }, []);

       return (
         <div>
             {
               items.length && items.map((item) => (<p>{item.name}</p>) )

             }
         </div>
       )
    }

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.