Jess Y.
Jess Y.

Reputation: 77

"Property json does not exist on type {}" TypeScript

I am VERY new to TypeScript and have a project to finish up by tomorrow. What I am trying to do is import my json file onto componentDidMount() and render that on the app. I think I am at least doing something right since when I hover over 'response', I get all the different keys and values in my JSON file. I am having trouble rendering it on my App.

Here is the code(and don't mind searchField, I am adding that later and have no errors about it atm):

import * as React from "react";
import GameCardList from "../GameCardList";
import logo from "./logo.svg";

export interface IGame {
  Name: string;
  ID: number;
  Slug: string;
}

interface IAppProps {
}

interface IAppState {
  games: Array<IGame>;
  searchfield: string;
}

export class App extends React.Component<IAppProps, IAppState> {
  constructor(props: Readonly<IAppProps>) {
    super(props);
    this.state = {
      games: [],
      searchfield: ""
    };
  }

  componentDidMount() {
    import("../games.json")
      .then( response => response.json())
      //^^where the error is
      .then((users: any) => {this.setState({ games: users}); });
  }

  onSearchChange = (event: { currentTarget: { value: any; }; }) => {
    this.setState({ searchfield: event.currentTarget.value });
  }

  render() {
    const { games, searchfield } = this.state;
    const filteredGames = games.filter(game => {
      return game.Name.toLowerCase().includes(searchfield.toLowerCase());
    });
    return !games.length ?
      <h1>Hello I am Loading!!</h1> :
      (
        <div className="tc">
            <GameCardList games={filteredGames} />
        </div>
      );
  }
}

// tslint:disable-next-line:no-default-export
export default App;

What is interesting is that I had this EXACT same code in my other TS project with the JSON file and it is working fine. Hmm what am I doing wrong?

Also, on the topic of importing JSON in typescript file, any resources or other advice I can follow?

Upvotes: 2

Views: 1879

Answers (1)

Bruno Monteiro
Bruno Monteiro

Reputation: 4519

You don't need the .json() there, since your response is already the object that you need.

You can test that by printing the response: console.log(response)

Upvotes: 1

Related Questions