Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Introduction/components/cert-challenge.tsx (TypeScript)

Code before:
  const certSlugTypeMapTyped: { [key: string]: string } = certSlugTypeMap;
  const superBlockCertTypeMapTyped: { [key: string]: string } =
    superBlockCertTypeMap;

  useEffect(() => {
    setIsCertified(
      currentCerts?.find(
        (cert: { certSlug: string }) =>
          certSlugTypeMapTyped[cert.certSlug] ===
          superBlockCertTypeMapTyped[superBlock]
      )?.show ?? false
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentCerts]);

  const certLocation = `/certification/${username}/${certSlug}`;

  const createClickHandler =
    (certSlug: string | undefined) => (e: MouseEvent<HTMLAnchorElement>) => {
      e.preventDefault();
      if (isCertified) {
        return navigate(certLocation);
      }
      return isHonest
        ? verifyCert(certSlug)
        : createFlashMessage(honestyInfoMessage);
    };
  return (
    <div>
      {isSignedIn && (
        <Button
          block={true}
          variant='primary'
          href={isCertified ? certLocation : `/settings#cert-${certSlug}`}
          onClick={() => (isCertified ? createClickHandler(certSlug) : false)}
        >
          {isCertified && userLoaded
            ? t('buttons.show-cert')
            : t('buttons.go-to-settings')}{' '}
          <span className='sr-only'>{title}</span>
        </Button>
      )}
    </div>
  );
};

CertChallenge.displayName = 'CertChallenge';

export default connect(
  mapStateToProps,
  mapDispatchToProps

Review comment (suggestion):
This `createClickHandler` function is called only when `isCertified` is `true`, meaning the first `if` condition is always hit and we never get to this `isHonest` condition. And if `isCertified` is `true`, we call `navigate` to send the user to the certification page, which is equivalent to setting `href={certLocation}` (which is already added).

I removed the `onClick` event handler as it is redundant. The button now renders:
- "Go to /settings" if the user hasn't claimed the cert
- "Show cert" if the user has claimed the cert

Tests for this rendering logic is already added here: https://github.com/freeCodeCamp/freeCodeCamp/blob/main/e2e/show-cert-from-superblock.spec.ts.

Code after:
import React, { useState, useEffect } from 'react';
import { useTranslation, withTranslation } from 'react-i18next';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { Button } from '@freecodecamp/ui';

import {
  certSlugTypeMap,
  superBlockCertTypeMap
} from '../../../../../shared/config/certification-settings';
import { SuperBlocks } from '../../../../../shared/config/superblocks';

import {
  isSignedInSelector,
  userFetchStateSelector,
  currentCertsSelector
} from '../../../redux/selectors';
import { User, Steps } from '../../../redux/prop-types';
import {
  type CertTitle,
  liveCerts
} from '../../../../config/cert-and-project-map';

interface CertChallengeProps {
  // TODO: create enum/reuse SuperBlocks enum somehow
  certification: string;
  fetchState: {
    pending: boolean;
    complete: boolean;
    errored: boolean;
    error: null | string;
  };
  isSignedIn: boolean;
  currentCerts: Steps['currentCerts'];
  superBlock: SuperBlocks;
  title: CertTitle;
  user: User;
}

const mapStateToProps = (state: unknown) => {
  return createSelector(
    currentCertsSelector,
    userFetchStateSelector,
    isSignedInSelector,
    (
      currentCerts,
      fetchState: CertChallengeProps['fetchState'],
      isSignedIn
    ) => ({
      currentCerts,
      fetchState,
      isSignedIn
    })
  )(state as Record<string, unknown>);
};

const CertChallenge = ({
  currentCerts,
  superBlock,
  title,
  fetchState,
  isSignedIn,
  user: { username }
}: CertChallengeProps): JSX.Element => {
  const { t } = useTranslation();
  const [isCertified, setIsCertified] = useState(false);
  const [userLoaded, setUserLoaded] = useState(false);

  const cert = liveCerts.find(x => x.title === title);
  if (!cert) throw Error(`Certification ${title} not found`);
  const certSlug = cert.certSlug;

  useEffect(() => {
    const { pending, complete } = fetchState;

    if (complete && !pending) {
      setUserLoaded(true);
    }
  }, [fetchState]);

  const certSlugTypeMapTyped: { [key: string]: string } = certSlugTypeMap;
  const superBlockCertTypeMapTyped: { [key: string]: string } =
    superBlockCertTypeMap;

  useEffect(() => {
    setIsCertified(
      currentCerts?.find(
        (cert: { certSlug: string }) =>
          certSlugTypeMapTyped[cert.certSlug] ===
          superBlockCertTypeMapTyped[superBlock]
      )?.show ?? false
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentCerts]);

  const certLocation = `/certification/${username}/${certSlug}`;

  return (
    <div>
      {isSignedIn && (
        <Button
          block={true}
          variant='primary'
          href={isCertified ? certLocation : `/settings#cert-${certSlug}`}
        >
          {isCertified && userLoaded
            ? t('buttons.show-cert')
            : t('buttons.go-to-settings')}{' '}
          <span className='sr-only'>{title}</span>
        </Button>
      )}
    </div>
  );
};

CertChallenge.displayName = 'CertChallenge';

export default connect(mapStateToProps)(withTranslation()(CertChallenge));