Home > Software engineering >  I keep getting NaN and then number in React.. how can I fix it?
I keep getting NaN and then number in React.. how can I fix it?

Time:10-05

enter image description here

const number = parseInt(props.detail.price,10)
        const toLocale = number.toLocaleString("ko-KR")
        
       

        console.log(toLocale)
    return (
        <div>
            <Descriptions title="상품정보" bordered>
                <Descriptions.Item label="가격">{toLocale} 원</Descriptions.Item>
                <Descriptions.Item label="판매수">{props.detail.sold}</Descriptions.Item>
                <Descriptions.Item label="열람수">{props.detail.views}</Descriptions.Item>
                <Descriptions.Item label="상품설명" span={2}>{props.detail.description} </Descriptions.Item>
            </Descriptions>  

 

      


**//I sent my props from here** 

    function Page(props) {    
        const productId = props.match.params.productId
        
        const [Product, setProduct] = useState({})
    
        
        
        useEffect(() => {
            axios.get(`/api/product/products_by_id?id=${productId}&type=single`)
            .then(response =>{
                setProduct(response.data[0])
               
            })
            .catch(err=> alert(err))
        }, [])    
    
        return (
            <div style={{width:'100%', padding: '3rem 4rem'}}>
                <div style={{display:'flex', justifyContent: 'center',alignItems: 'center', paddingBottom:'40px'}}>
                     <h1 style={{fontWeight:900}}>{Product.title}</h1> 
                </div>
                    <br/>
                    <br/>
    
                    <Row gutter={[16,16]}>
    
                        <Col sm={24} lg={12} ><ProductImage detail={Product}/></Col>
                        <Col sm={24} lg={12}><ProductInfo detail={Product}/></Col>
                    </Row>
                    
    
                </div>
            
            
        )
    }
    
    export default Page
       

The price keeps showing NaN and then number.. I tried to use replace() but it doesn't work. I console Product from useState and it returns an empty obeject and the proeject object.. how can this happen ?

what should I do to solve this ?

CodePudding user response:

Can you console log props & share the object we can find the exact reason for returning the NaN value. parseInt('non-number',10) will return the NaN value.

You can refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt this link for more details.

CodePudding user response:

according to my knowledge its the issue of rendering lately. Do that {props?.detail?.sold} or {props?.detail?.views}

Put question mark(?) Before accessing element in the object. It ensures that variable should render after getting the object..

CodePudding user response:

The problem is, detail is undefined until your Axios request comes back. This causes number to be NaN because parseInt(undefined) is NaN

You should implement some kind of loading state in the Page component. The most basic example would be to render null while loading.

I would recommend changing the initial state of Product to be undefined instead of {}. Then you can determine if your request is loading based on whether Product is undefined. If it is loading you can simply return null (or a loading spinner, for example).

Here's what that might look like:

function Page(props) {    
    const productId = props.match.params.productId
    
    // Notice: initial state is undefined, instead of `{}`
    const [Product, setProduct] = useState()

    
    
    useEffect(() => {
        axios.get(`/api/product/products_by_id?id=${productId}&type=single`)
        .then(response =>{
            setProduct(response.data[0])
            
        })
        .catch(err=> alert(err))
    }, [])

    // While request is loading, return null
    // Alternatively, you can render some kind of loading state like a spinner or blank table
    if (!Product) {
      return null;
    }

    return (
        <div style={{width:'100%', padding: '3rem 4rem'}}>
            <div style={{display:'flex', justifyContent: 'center',alignItems: 'center', paddingBottom:'40px'}}>
                  <h1 style={{fontWeight:900}}>{Product.title}</h1> 
            </div>
                <br/>
                <br/>

                <Row gutter={[16,16]}>

                    <Col sm={24} lg={12} ><ProductImage detail={Product}/></Col>
                    <Col sm={24} lg={12}><ProductInfo detail={Product}/></Col>
                </Row>
                

            </div>
        
        
    )
}
  • Related