-1
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useMount, useAsyncFn } from 'react-use';
import { Grid } from '@material-ui/core';
import { useTranslation } from 'react-i18next';

import LegalEntitiesService from 'shared/services/LegalEntitiesService';
import { TextField } from 'shared/components/Form';

const LegalEnityInformation: React.FC= () => {
  const { legalEntityId } = useParams();
  const { t } = useTranslation();
  const [legalEntity, setLegalEntity] = useState<any>({
    id: null,
    name: '',
    address: '',
    municipalityCode: '',
    eik: '',
    municipality: { name: '' },
  });

  useMount(() => {
    if (legalEntityId) {
      fetchData();
    }
  });

  const [legalEntityData, fetchData] = useAsyncFn(
    () => LegalEntitiesService.getLegalEntity(legalEntityId),
    []
  );

  useEffect(() => {
    if (
      !legalEntityData.loading &&
      legalEntityData.value &&
      !legalEntityData.error
    ) {
      const data: any = legalEntityData.value.data;
      setLegalEntity({ ...data });
    } else if (legalEntityData.error) {
      // console.log(legalEntityData.error.message);
    }
  }, [legalEntityData]);

  return (...);
};

export default LegalEnityInformation;

I cannot understand why property legalEntityId doesnt exist on type {}

Shall I add interface/constructor?

Let's define legalEntityId to be a number, maybe it is gonna be better?

sth like interface Props { legalEntityId? = number} ?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
  • React Router documentation says "useParams returns an object of key/value pairs of URL parameters". My idea is to check what is the content of that object (maybe console.log) and see if legalEntityId property exists. –  Apr 15 '21 at 14:18
  • Does this answer your question? [useParams in TypeScript does not allow destructuring](https://stackoverflow.com/questions/64517983/useparams-in-typescript-does-not-allow-destructuring) – Linda Paiste Apr 15 '21 at 17:08

1 Answers1

0

You are accessing the legalEntityId from the URL string so actually it will always be a string instead of a number. If you want a number then you will have to convert it with parseInt.

useParams is a generic and it does not know what params it can expect to find on the current URL, so you must tell it.

To get string | undefined:

const { legalEntityId } = useParams<{ legalEntityId?: string }>();

To get number | undefined:

const params = useParams<{ legalEntityId?: string }>();
const legalEntityId = params.legalEntityId ? parseInt(params.legalEntityId) : undefined;
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102