Home > Blockchain >  Can someone please help me fix match.params.id using useEffect hook in v6?
Can someone please help me fix match.params.id using useEffect hook in v6?

Time:08-30

Can someone please help me fix match.params.id using useEffect hook in v6? I get a blank page when I do this so I need help. The code is below:

import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import { getProfileById } from '../../actions/profile';

const Profile = ({ getProfileById, profile: { profile, loading }, auth, match }) => {
  useEffect(() => {
    getProfileById(match.params.id);
  }, [getProfileById]);
  return (
  <div>profile</div>
  );
};

Profile.propTypes = {
    getProfileById: PropTypes.func.isRequired,
    profile: PropTypes.object.isRequired,
    auth: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
    profile: state.profile,
    auth: state.auth
});
export default connect(mapStateToProps, { getProfileById })(Profile);

CodePudding user response:

In react-router-dom@6 there are not any route props, so there isn't any match prop. Use the useParams hook to access the id route path param.

import React, { Fragment, useEffect } from 'react';
import { useParams } from 'react-router-dom'; // (1) <-- import useParams hook
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import { getProfileById } from '../../actions/profile';

const Profile = ({ getProfileById, profile: { profile, loading }, auth }) => {
  const { id } = useParams(); // (2) <-- access id path param

  useEffect(() => {
    getProfileById(id); // (4) <-- pass to callback
  }, [getProfileById, id]); // (3) <-- add as dependency

  return (
    <div>profile</div>
  );
};

Profile.propTypes = {
  getProfileById: PropTypes.func.isRequired,
  profile: PropTypes.object.isRequired,
  auth: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
  profile: state.profile,
  auth: state.auth
});

export default connect(mapStateToProps, { getProfileById })(Profile);
  • Related