So I have a React Native application using TypeScript, with an error that's driving me crazy.
Basically, there is a Searchable List. It is initiated with an Array of values. Once the user types in a SearchBar, the initiated Array is filtered, returning an updated Array.
However, TypeScript gives me the error: Type '{ id: string; name: string; selected: boolean; }[]' provides no match for the signature '(prevState: undefined): undefined'.
I am confused because I don't know where this '(prevState: undefined): undefined'
actually comes from and why. Do you know what I am doing wrong here? Help will be much appreciated.
Here is the code:
const defaultChoices = [
{
id: '1',
name: 'default',
selected: false,
},
];
let choicesList;
const getChoicesList = () => {
if (listName === 'include') {
choicesList = Object.values(includeChoices).map(choice => ({
...choice,
}));
} else if (listName === 'exclude') {
choicesList = Object.values(excludeChoices).map(choice => ({
...choice,
}));
}
};
const [filteredChoicesList, setFilteredChoicesList] = useState(choicesList);
useEffect(() => {
getChoicesList();
}, []);
useEffect(() => {
let choices = defaultChoices;
if (listName === 'include') {
choices = includeChoices;
} else if (listName === 'exclude') {
choices = excludeChoices;
} else {
choices = defaultChoices;
}
const newChoices = choices.filter(item => {
const itemData = `${item.name.toUpperCase()}`; // ignore Uppercase/Lowercase and make equal
const textData = query.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setFilteredChoicesList(newChoices); // error occurs for "newChoices"
}, [effect]);
The problem is, you have set the choicesList
as undefined. and getChoicesList
is called on the first initialization of component but before that the state us being set where the choicesList
is undefined.
Update the part of your code as
let choicesList: any[] = [];
const getChoicesList = () => {
let data: any[] = [];
if (listName === 'include') {
data = Object.values(includeChoices).map(choice => ({
...choice,
}));
} else if (listName === 'exclude') {
data = Object.values(excludeChoices).map(choice => ({
...choice,
}));
}
return data;
};
const [filteredChoicesList, setFilteredChoicesList] = useState<any[]>(choicesList);
useEffect(() => {
const updatedList = getChoicesList();
setFilteredChoicesList(updatedList)
}, []);
Now, you'll have the filteredChoicesList
with data you need and you shouldn't have any compilation error.
Another thing is, create an interface and replace any
with that interface in the state and while defining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With