Reputation: 1588
I have the following object.
const data = [
{
key: '1',
name: 'John Brown',
date: 'Mon Oct 31 2013 00:00:00 GMT-0700 (PDT)',
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Joe Black',
date: 'Mon Oct 31 2014 00:00:00 GMT-0700 (PDT)',
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Jim Green',
date: 'Mon Oct 31 2011 00:00:00 GMT-0700 (PDT)',
address: 'Sidney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
date: 'Mon Oct 31 2010 00:00:00 GMT-0700 (PDT)',
address: 'London No. 2 Lake Park',
},
];
And this state
const [usersData, setUsersData] = React.useState([]);
I'm trying to setup its data with an useEffect on component mount.
React.useEffect(() => {
setUsersData(result => [...result, data[0]])
props.setLoading(false);
}, []);
But im having an issue with the setUsersData
Argument of type '(result: never[]) => { key: string; name: string; date: string; address: string; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'. Type '(result: never[]) => { key: string; name: string; date: string; address: string; }[]' is not assignable to type '(prevState: never[]) => never[]'. Type '{ key: string; name: string; date: string; address: string; }[]' is not assignable to type 'never[]'. Type '{ key: string; name: string; date: string; address: string; }' is not assignable to type 'never'.ts
UPDATE:
This is what I have currently.
const data = .... is still the same
I changed the useState to
const [usersData, setUsersData] = React.useState<any[]>([]);
And I do this now
React.useEffect(() => {
setUsersData(result => [...result, data[0]])
props.setLoading(false);
}, []);
But this way it only adds the elemtn 0 to my array, and Im trying to add all the elements contained in data
Upvotes: 2
Views: 1358
Reputation: 8751
any
try const [usersData, setUsersData] = React.useState<any[]>([]);
React.useEffect(() => {
setUsersData(result => [...result, ...data])
props.setLoading(false);
}, []);
Upvotes: 2
Reputation: 2050
const [usersData, setUsersData] = React.useState([]);
Issue here is that typescript infer type of []
as never[]
which means empty array.
So to fix issue you have to specify type providing generic argument to useState
:
type Item = {
key: string,
name: string,
date: string,
address: string,
}
// It will work even without specifying type here
const data: Item[] = {
//
}
const [usersData, setUsersData] = React.useState<Item[]>([]);
Providing type for useState
says to typescript that this array of Item
's event if it's empty for now.
Upvotes: 3