skip to Main Content

What I am doing is reading a JSON file located in the public directory of my React project in the CardContainer component, as can be seen below:

import { useAsync } from "react-async";

type ProjectData = {
    title: string,
    desc: string,
    website: string,
    repo: string,
    tags: Array<string>
}

type ProjectContainerData = {
    projects: Array<ProjectData>
}

async function getData() {
  let output: ProjectContainerData | undefined = undefined;
  await fetch("/myProjects.json")
    .then((response) => response.text())
    .then((data) => {
      output = JSON.parse(data);
    });
  return output;
}

function CardContainer() {
  const { data, error, isPending } = useAsync(getData);
    for (let project of data?["projects"]) {
      // error is here
    }
  return <></>;
}

export default CardContainer;

When I am editing my code, I see the ':' expected.ts(1005) error. When I try to compile it with npm start, I see the same thing:

ERROR in src/components/CardContainer.tsx:27:42
TS1005: ':' expected.
    25 | function CardContainer() {
    26 |   const { data, error, isPending } = useAsync(getData);
  > 27 |     for (let project of data?["projects"]) {
       |                                          ^
    28 |
    29 |     }
    30 |   return <></>;

My TypeScript version is 4.9.5. Is there any way to easily avoid this error?

2

Answers


  1. Chosen as BEST ANSWER

    Update: The error goes away when I change this:

    const { data, error, isPending } = useAsync(getData);
    

    to this:

    const { data, error, isPending } = useAsync<ProjectContainerData | any>(getData);
    

    and when I change this:

    for (let project of data?["projects"]) {
    

    to this:

    for (let project of data.projects) {
    

  2. ?[...] operator does not exist, the right syntax for it is ?.[...]

    Hence ?.['projects'], or ?.projects

    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search