Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useState with Typescript while passing empty array

I am trying to convert my JSX code into typescript (TSX) and having a difficulty in passing the interface while using useState hook. All I want is an empty array Interface in my state and on updating i am pushing the object to the Array one by one.

I am getting Typed error on updating the count "Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction'. Type 'any[]' is not assignable to type '(prevState: IData) => IData'. Type 'any[]' provides no match for the signature '(prevState: IData): IData'"

Here is the code i have done:

sample.tsx

const interface IData {
id: number
value: string
}
const Sample = () => {

let [count, setCount] = useState<IData>([]);       <------------ Want to know how to pass the blank interface or Array and also how to update interface once values are pushed to the Array

const addCount = () => {
    setCount([...count, {
        id: count.length,
        value: 'Condition ' + count.length      
    }])
}

const handleRemove = (id:number) => {
    console.log(id);
    const count_upd = count.filter((item:any) =>  item.id != id);
    setCount(count_upd);
}


return(
    <React.Fragment>
        <Container>
        { Array(count).fill(<ConditionSeg Data={count.map((item:IData) =>  (
                    item.id,item.value
                ))}
                HandleRemove ={handleRemove}
                />)}
        </Container>
        <Container>
            <Button 
                onClick={addCount}>
                Click me</Button>
        </Container>
    </React.Fragment>
)

}

P.S. Don't Mind the type errors.

like image 508
Asnau Nauticas Avatar asked Jul 25 '26 04:07

Asnau Nauticas


1 Answers

So as far as I can tell, you want to store an array of values of type IData. In this case you should use

let [count, setCount] = useState<IData[]>([]);

This means, you are storing an array of values of type IData. In your case above you forgot the array brackets, so setCount would actually expect a single object of type IData instead of an array.

like image 79
Peter Lehnhardt Avatar answered Jul 27 '26 11:07

Peter Lehnhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!