I am using react and typescript. I am trying to get unique values from array using 'new Set' and setting the values of a useState. but I am getting the below error
argument of type 'Set<string>[]' is not assignable to parameter of type 'SetStateAction<String[]>'.
Type 'Set<string>[]' is not assignable to type 'String[]'.
Type 'Set<string>' is missing the following properties from type 'String': charAt, charCodeAt, concat, indexOf, and 43 more.ts(2345)
Below is my code
const [subCategories, setSubCategories] = useState<String[]>([]);
useEffect(() => {
return setSubCategories(Array.from([new Set(products.map((p) => p.category))]));
}, []);
products is an array array of object
CodePudding user response:
You have an extra set of brackets []
inside Array.from() call. You want to do Array.from(new Set(['a', 'b', 'c']))
;
Another thing is the string type in typescript is represented as string
. String
is the class. I can't really think of anything immediately wrong with using String
, but it's probably not a good idea, definitely uncommon.
CodePudding user response:
From the MDN docs:
The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.
You are passing an array containing the set into Array.from()
instead of the set itself, which is already an iterable object:
return setSubCategories(Array.from(new Set(products.map((p) => p.category))));