skip to Main Content

I am having the following issue. I want to make a fetch that gets json data. use a parser to parse that data to an array of a certain type that is given to the parser as an argument. Im very new to React and i would really appreciate some help. Thanks in advance!

This is page.tsx:

"use client";
import CollapsingTable from "@/components/admin-dashboard/CollapsingTable";
import PageHeading from "@/components/admin-dashboard/PageHeading";
import fetchData from "@/lib/services/fetchData";
import parseData from "@/lib/services/parseData";
import { useEffect, useState } from "react";

export default function ProductPage() {
  const dataUrl = "https://jsonplaceholder.typicode.com/users";
  const [userList, setUsers] = useState<User[]>([]);

  useEffect(() => {
    const x = fetchData(dataUrl).then((json) => {
      const users: User[] | null = parseData<User>(json) || [];//this does not work
      console.log(users);
      console.log(typeof users[0]);
      setUsers(users);
      console.log(userList);
    });
  }, []);

  return (
    <>
      <PageHeading
        title={"Product Management"}
        href={"products"}
        children={undefined}
      ></PageHeading>
      {/* <CollapsingTable data={data} /> */}
    </>
  );
}

This is fetchData.ts:

export default async function getAllObjects(url: string) {
  const response = await fetch(url);

  if (!response.ok) throw new Error("Fetching objects failed");
  return response.json();
}

This is parseData.ts:

export default function parseAllObjects<T>(jsonString: string): T[] | null {
  try {
    return JSON.parse(jsonString) as T[];
  } catch (error) {
    console.error("Error parsing JSON:", error);
    return null;
  }
}

And this is my type (in this case User):

type User = {
  id: number;
  name: string;
  username: string;
  email: string;
  address: {
    street: string;
    suite: string;
    city: string;
    zipcode: string;
    geo: {
      lat: string;
      lng: string;
    };
  };
  phone: string;
  website: string;
  company: {
    name: string;
    catchPhrase: string;
    bs: string;
  };
};

The error i currently get in the browser is as follows:

Error parsing JSON: SyntaxError: Unexpected token 'o', "[object Obj"... is not valid JSON

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution, needed to parse the json data using this instead of a type:

    {data.map((person, index) => (...etc...))}
    

  2. In this line also add await, Like this:

    await const x = fetchData(dataUrl).then((json) => {

    And I think after this you have to change this export default function ProductPage() { to export default async function ProductPage() { (async is added due to await)

    Thanks, try and let me know if this works!

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