I use react hooks to update, but notice error when setState.
Argument of type '{ alertRules: any; }' is not assignable to parameter of type 'SetStateAction'. Object literal may only specify known properties, and 'alertRules' does not exist in type 'SetStateAction'.ts(2345)
Here is my code.
import React, { useState, useEffect } from 'react';
import { FieldArray } from 'redux-form';
import { CoordinateSelect } from '~/fields';
import lodash from 'lodash';
import { connect } from 'react-redux';
import { filterDispatchers } from '~/actions';
import t from '~/locale';
interface Props {
getAlertRules(o: object): Promise<any>;
}
type Alert = {
...
}
const connector = connect(
null,
filterDispatchers('getAlertRules'),
);
const AlertRuleForm = (props: Props) => {
const [alertRules, setAlertRules] = useState<Alert[]>([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const actionResult = await props.getAlertRules({ limit: -1 });
const alertRules = lodash.get(actionResult, 'response.alertRules', []);
setAlertRules({ alertRules }); //Error form here
};
const groupedRules = lodash.groupBy(alertRules, 'resourceType');
const levelTypes = lodash.uniq(alertRules.map((alert: Alert) => alert.level));
return (
<FieldArray
name="alertRules"
component={CoordinateSelect}
label={t('å‘Šè¦è§„则')}
firstOptions={lodash.keys(groupedRules)}
secondOptions={groupedRules}
thirdOptions={levelTypes}
required
/>
);
};
export default connector(AlertRuleForm);
the error is when set state
Argument of type '{ alertRules: any; }' is not assignable to parameter of type 'SetStateAction'. Object literal may only specify known properties, and 'alertRules' does not exist in type 'SetStateAction'.ts(2345)
Short Answer :- Remove the curly braces from the setAlertRules statement , as it is leading to an inconsistency between the type
of setAlertRules
at the definition and its usage.
This is feature of ES6 known as Object literal Shorthand.
At the time of Defining the alertRules the type of setAlertRules is SetStateAction< Alert [ ] > . And you are trying to give it value of type {alertRules: any} , which is leading to the error .
The value passed to alertRules
is an object with key alertRules
and its value as the array of type Alert
.
So ,remove the curly brace as it is converted to something this
setAlertRules({ alertRules: alertRules });
// now {alertRules: any} this thing will make sense
try this code for updation of alertRules .
// see no curly braces .
setAlertRules( alertRules );