colin_dev256
colin_dev256

Reputation: 815

React/Typescript: How to get json file data

How can I read data from a json file in state? I know how to do this in react only but failing to do it in react using typescript. Should I place it in state in the first place if it's not going to change anyways?

import * as React from 'react';
import * as data from '../../team.json';

interface Props {
  //props
}

interface State {
   nextRacers: Array<object>;
   jockeys: Array<any>;
}

console.log(data) // I can see my data here in dev tools

export class Race extends React.Component<Props, State> {

  constructor(props: Props) {
      super(props);
      this.state = {
          jockeys: data, 
          nextRacers: [],
      };
  }
  
}

Error I get;

Type '{ jockeys: typeof ".json"; nextRacers: never[]; }' is not assignable to type 'Readonly'. Types of property 'jockeys' are incompatible. Type 'typeof ".json"' is not assignable to type 'any[]'. Property 'includes' is missing in type 'typeof "*.json"'.

I'm new to typescript & react and the syntax is still messing with my head.

Upvotes: 1

Views: 8340

Answers (1)

Alex Yuly
Alex Yuly

Reputation: 180

First, you need to cast data to any, and then you need cast it again to the type of the jockeys field, which is Array<any>. Try updating the assignment to this.state like so:

this.state = {
    jockeys: data as any as Array<any>, 
    nextRacers: [],
};

Upvotes: 0

Related Questions