How to fetch and display data from json file in react typscript

Viewed 302

I want to display data as list in typescript, I am able to fetch but cannot display it.I am using map to access array of json objects

//json file
[
  {
    "id": "6s",
    "name": "Iphone6s"
  },
  {
    "id": "6",
    "name": "Iphone6"
  },
  {
    "id": "11",
    "name": "Iphone11"
  },
  {
    "id": "11pro",
    "name": "Iphone11Pro"
  },
  {
    "id": "11promax",
    "name": "Iphone11Max"
  },
  {
    "id": "12",
    "name": "Iphone12"
  }
]

//App.tsx
import * as React from "react";
import "./styles.css";
import data from "./data.json";
console.log(data);

interface Phone {
  id: string;
  name: string;
}
export default function App() {
  return (
    <div className="App">
      <h1>Welcome to Apple Store!</h1>
      {data.map((item, i) => {
        return <h2>Phone:{data.name}</h2>;
      })}
    </div>
  );
}

can have look here: https://codesandbox.io/s/iphonestore-zguzp?file=/src/App.tsx:0-367

1 Answers
{data.map((item, i) => <h2 key={i}>Phone:{item.name}</h2>)}

Also ur interface should be like this :

interface IPhone {
  id: string;
  name: string;
}

type PhoneData = IPhone[];
Related