Home > Net >  useParams() can not parseInt to number typescript
useParams() can not parseInt to number typescript

Time:07-29

the heroid type is string, I try to convert to number always show error.

code:

import useHero from '../../hooks/useHero';
import {useParams} from 'react-router-dom'


function Herospages() {
    const {heroId} = useParams() 
   const value = parseInt(heroId)
   const{data,isLoading} =  useHero(value)
...}

the useHero is my hook from useQuery

error:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'

CodePudding user response:

const value = parseInt(heroId!)

makes your variable non-nullable

CodePudding user response:

I guess your problem is here:

const {heroId} = useParams() 

If you hover over heroId i guess it will display you const hero: string | undefined

This means heroId could possibly be undefined

But parseInt() expects an string

This means: It expects string but you pass in string | undefined

You need to check first if its undefined:

const {heroId} = useParams() 
if(heroId === undefined) return
  • Related