I want to change value of state with useState hook, but I've never worked with useState hook in functional component before, and I get a very strange error. Even though I define all of my variables as string[], it tries to define whole array as number.
import * as React from 'react'
import { NextPage } from 'next'
const IndexPage: NextPage = () => {
const [countries, setCountries] = React.useState<string[]>([])
return (
<>
{
["Dallas", "Oregon", "New York", "California"].map((x: string) =>
<button onClick={() => setCountries(countries.push(x))}>
<span>{x}</span> ^^^^^^^^^^^^^^^^^
</button>
)
}
<>
)
}
Here is strange error I get:
(method) Array<string>.push(...items: string[]): number
"Argument of type 'number' is not assignable to parameter of type 'SetStateAction<string[]>'.ts(2345)"
Array.push returns a number so you have to change your code to this
import * as React from 'react'
import { NextPage } from 'next'
const IndexPage: NextPage = () => {
const [countries, setCountries] = React.useState<string[]>([])
return (
<>
{
["Dallas", "Oregon", "New York", "California"].map((x: string) =>
<button onClick={() => {
// either this
setCountries(countries.concat(x))
// or
setCountries([...countries, x]
}>
<span>{x}</span>
</button>
)
}
<>
)
}
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