Cannot read properties of undefined (reading 'params')

I am writing a CRUD application in Java and React. I have an UpdateRecordComponent in react where I am using it to update a specific record. However everytime I click on the button to edit the record, it gives me the error "Cannot read properties of undefined (reading ‘params’)".

The code is as below:

class UpdateContractorComponent extends Component {
    constructor(props) {
        super(props);
        this.state={contractorId:'', contractorName:'', phoneNumber:'', email:''};
    }
    componentDidMount() {
        const contractorId = this.props.match.params.contractorId;
        if(contractorId > 0) {
            this.getContractorById(contractorId);
        }
    }
    getContractorById = (contractorId) => {
        ContractorService.getById(contractorId).then(
            (response) => {
                console.log(response);
                this.setState({
                    contractorId:response.data.contractorId,
                    contractorName:response.data.contractorName,
                    phoneNumber:response.data.phoneNumber,
                    email:response.data.email
                });
            }, (error) => {
                console.log(error);
                alert("Operation Failed");
            }
        );
    }
    onInputChange = e => {
        this.setState({
            [e.target.name]:e.target.value
        });
    }
    formHandle = e => {
        e.preventDefault();
        const contractor = {
            contractorName:this.state.contractorName,
            phoneNumber:this.state.phoneNumber,
            email:this.state.email
        };
        ContractorService.update(this.state.contractorId, contractor).then(
            (response) => {
                console.log(response);
                alert("Contractor Updated Successfully");
            }, (error) => {
                console.log(error);
                alert("Operation Failed");
            }
        );
    }

The error points to this line:

 const contractorId = this.props.match.params.contractorId;

I am using the latest versions of all the dependencies like react-router-dom, reactstrap, etc. Does anyone know how to fix it?

>Solution :

As the error says, the object "params" is undefined. The issue can be raised for multiple reasons (and I can’t guess which they are since you didn’t insert how your code pass information through the route).

The first thing to check is: are you overriding the match property?

When you spread {...props} your match prop overrides react-router’s match. [Source: Original answer]

    <Route path='/champions/:id' render={(matchProps) =>
      <ChampionDetails
        {...matchProps}
        {...this.props}
        handleMatch={this.handleMatch}
      />
    }/>

If this is not your case I leave you a link that can help you in troubleshooting.

How to access 'this.props.match.params' along with other props?

Leave a Reply