Home > Mobile >  How can I remove type 'false' inside a setState generic used in react?
How can I remove type 'false' inside a setState generic used in react?

Time:07-18

Hi I'm trying to use useState and handling a state with generics. Inside a setState, I manipulated a fetched array with filter function and as you know it returns false.

so... I'll show my codes.

 const [mapItemsState, setMapItems] = useState<{ [k: string]: number | string }[]>([]);

 setMapItems(
     Object.entries(data)?.map(
        ([key, value]) =>
               Object.keys(mapItemListKor).includes(key) && {
               [key]: value as string | number,
        },
     )
     .filter(Boolean)        // I erased a false here!
 )

and this code returns this error Argument of type '(false | { [x: string]: string | number; })[]' is not assignable to parameter of type 'SetStateAction<{ [k: string]: string | number; }[]>'.

I removed false using filter but it still detect false.

How can I handle it?

CodePudding user response:

 const [mapItemsState, setMapItems] = useState<{ [k: string]: number | string }[]>([]);

 setMapItems(
     Object.entries(data).filter(Boolean)?.map(
        ([key, value]) =>
               Object.keys(mapItemListKor).includes(key) && {
               [key]: value as string | number,
        },
     )
 )

The issue you were having is that you were not filtering the array before it got mapped, meaning that the falses still get passed into the .map

CodePudding user response:

Anyway I solved this problem as below.

setMapItems(
                Object.entries(data)
                    .filter(([key]) =>
                        Object.keys(mapItemListKor).includes(key),
                    )
                    .map(([key, value]) => {
                        return { [key]: value as string | number };
                    }),
            );
  • Related