Home > Software design >  React Typescript - Argument of type 'string' is not assignable to parameter of type within
React Typescript - Argument of type 'string' is not assignable to parameter of type within

Time:08-05

I have a React web app I want to pull in two URLs containing API data and displaying said data. One URL is English and one is French.

To pull in the French API data, I need to append "?accept-language=fr-ca" to the end of the original English URL:

let param = "?";
let french = param   "accept-language=fr-ca";

And then when using setData:

setData(response.data   french);

When appending french to setData above, I receive the following TypeScript error:

Argument of type 'string' is not assignable to parameter of type 'SetStateAction<InspectionReportData[] | null | undefined>'.

How can I fix this TypeScript error?

Full code below:

interface Props_PIReport {
  lang: string;
  jsonDataProduct: Type_jsonModelDetails | undefined;
}

const PeriodicAnnualInspectionReport = ({
  lang,
  jsonDataProduct,
}: Props_PIReport) => {
  // Make a call to fetch the inspection report data within the original API
  const [data, setData] = useState<InspectionReportData[] | null>();

  useEffect(() => {
    let param = "?";
    let french = param   "accept-language=fr-ca";
    if (lang === "fr") {
      if (jsonDataProduct) {
        axios.get(jsonDataProduct["inspection-link"]).then((response) => {
          setData(response.data   french);
        });
      }
    } else {
      ...
    }
  }, []);

return (
    ...
  );
};

CodePudding user response:

You're not calling setData with the right type of argument.

useState<InspectionReportData[] | null>()

This line means you'll call setState with one of two types: null or an array of InspectionReportData.

You are actually calling it with a string type: setData(response.data french);

You need to either make it accept a string or change the way you're calling it.

This is exactly what the error message means.

  • Related