ReactJS: Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'
I am fetching data from API and populating the input texts from the fretched email. I'm using bullet and setBullet to maintain the state. The problem is that I must define an initial item into the use state like this:
const [bullet, setBullet] = useState(['Temp']);
But defining it like this it obviously adds "Temp" as the first input and then all emails follow. But if I define the state like this:
const [bullet, setBullet] = useState([]);
I get errors in onChangeHandler and map function in useEffect.
const onChangeHandler = (index: number, value: string) => {
setBullet((bullets) =>
bullets.map((bullet, i) => (i === index ? value : bullet))
);
};
useEffect(() => {
fetch(
"https://reqres.in/api/users?page=2")
.then((res) => res.json())
.then((json) => {
json.data.map((data: any) => {
setBullet((bullets) => [...bullets, data.email]);
return console.log(data.email);
})
})
}, [])
Error comes in setState function:
Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type '(bullets: never[]) => string[]' is not assignable to type '(prevState: never[]) => never[]'.
Type 'string[]' is not assignable to type 'never[]'.
Type 'string' is not assignable to type 'never'
To summarise this is what I'm getting. I want to remove the 'Temp' bullet from it.
Any help will be much appreciated.
Thank You
Solution 1:
You can pass whichever type you want to useState
using generics. If you don't pass in the type, useState
will try to infer it from the initial value. Since you're passing in an empty array, the type can't be inferred automatically so you have to do it manually:
const [bullet, setBullet] = useState<string[]>([]);