Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js useState with Array.push method on functional component

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)"
like image 767
Abdulsamet Kurt Avatar asked Oct 29 '25 17:10

Abdulsamet Kurt


1 Answers

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>
        )
      }
    <>
  )
}
like image 165
Ruben van der Veen Avatar answered Oct 31 '25 07:10

Ruben van der Veen



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!