React - undefined props error when rendering functional component

Viewed 155

Sorry for the repetitive question. I have searched everywhere imaginable and I can't figure this out. I'm new to React and I've noticed that there are several ways to go about every problem. My current issue is that I'm trying to convert a working class component to a function. The webpage was rendering just fine with the database content until I attempted to change the class to a function. Can anyone assist with isolating where the disconnect is? I'm sure there are several parts of the code that I did not transfer over to a function format.

The error I'm getting is:

Uncaught TypeError: Cannot read properties of undefined (reading 'props')

Below is the component that was working until I changed it from class to function:

import React, { Fragment, useEffect } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getDevices } from '../../actions/deviceActions';

export const Devices = () => {
  
  const propTypes = () => ({
    deviceState: PropTypes.array.isRequired,
    getDevices: PropTypes.func.isRequired,
  });

  useEffect(() => {
    this.props.getDevices();
  }, []);

  return (
    <Fragment>
      <h2>Device List</h2>
      <div>
        { this.props.deviceState.map(device => (
          <h1 key={device.id}>{device.make}</h1>
        )) }
      </div>
    </Fragment>
  );
}

const mapStateToProps = state => ({
  deviceState: state.device.device
});

export default connect(mapStateToProps, { getDevices })(Devices);
1 Answers

You don't seem to be passing in your props at all..

Also, you don't want multiple exports. So get rid of the initial export and simply set the Devices variable to your functional component.

That being said, when using props in a functional component, you no longer need to use this for context. Simply pass props as a parameter and access it directly:

const Devices = (props) => {

  const propTypes = () => ({
    deviceState: PropTypes.array.isRequired,
    getDevices: PropTypes.func.isRequired,
 });

useEffect(() => {
  props.getDevices();
}, []);

return (
<Fragment>
  <h2>Device List</h2>
  <div>
    { props.deviceState.map(device => (
      <h1 key={device.id}>{device.make}</h1>
    )) }
  </div>
</Fragment>
);
}
Related