1

I have the following code and every time I try to access the state inside of the return I got a

TypeError: Cannot read property '#property' of null

import React, {useEffect, Fragment} from 'react'
import {Row, Col} from 'react-bootstrap'
import {connect} from 'react-redux';
import PropTypes from 'prop-types'
import {getProduct} from '../../actions/produto'


const Product = ({getProduct, match, produto: {produto}}) => {

    useEffect(() => {
        getProduct(match.params.id);
    }, [getProduct, match.params.id]);

    console.log(produto);
    return (
        <Fragment>
            <Row>
                <Col>
                    {produto.name}
                </Col>                
            </Row>
        </Fragment>
    )
}

Product.propTypes = {
    getProduct: PropTypes.func.isRequired,
    produto: PropTypes.object.isRequired
}

const mapStateToProps = (state) =>({
    produto: state.produto
})

export default connect(mapStateToProps, {getProduct})(Product)

However if I console.log(produto) before the return I can get the real state value. The state has the correct value until I try access {produto} inside the return statement. When I do that it changes to null. Can someone explain me why does this happens and how to fix it?

Thank you

2 Answers2

0

This is my reducer

   import {
        GET_PRODUCT,
        GET_PRODUCTS,
        GET_PRODUCT_ERROR,
        PRODUCT_LOADED
    } from '../actions/types'

    const initialState = {
        produto: null,
        produtos: []
    }

    export default function(state = initialState, action){
        const {type, payload} = action;
        switch(type){
            case GET_PRODUCT:
            case PRODUCT_LOADED:
                return{
                    ...state,
                    produto: payload
                }
            case GET_PRODUCTS:
               return {
                ...state,
                produtos: payload
               }
            case GET_PRODUCT_ERROR:
                return{
                    ...state,
                    produto: null,
                    produtos: null
                }
            default: 
                return state
        }
    }
0

I found the answer here: React state is null inside of return

@mo-ismat said: the reason this happens is because the api call is asynchronus, it doesn't populate the state immediately, so the render happens first and tries to read .current from the initial state null

That's actually worked. I added a conditional before rendering the state {produto && produto.name} value and it worked.

Thanks for all the help guys

  • Right link to the answer: https://stackoverflow.com/questions/57263525/useeffect-not-being-called-and-not-updating-state-when-api-is-fetched – Eliezer Barbosa Jun 06 '20 at 18:41