Home > Back-end >  React useState to JSON object type
React useState to JSON object type

Time:08-18

I have a JSON data file that is imported with

import data from "../data.json";

It looks like this:

[
  {
    "name": "Emery",
  },
  {
    "name": "Astrid",
  },
  {
    "name": "Monto",
  }
]

A button click sets a state to the an item of the JSON array (e.g. Array item 2). My issue here is I don't know how to define the useState in a Typescript manner as I get the error that the name property does not exist. I know I could define a separate type definition file. Since Typescript is smart enough to know all imported JSON types and my state is part of that JSON, I was thinking that it must be possible without a definition file? Am I wrong here?

CodePudding user response:

I think the real problem here is not with the JSON import since it shouldn't be a problem for TypeScript to tell that the objects in this data array, all have a name property.

Actually, it is necessary to set the type for your useState object. And this might be the reason you have that error. First, you have to define the type. For this object, it looks like the following should be suitable:

type MyType = { name: string }

Next, you have to add the type to useState():

const [state, setState] = useState<MyType[]>(data);

Here [] means state is an array of objects of type MyType.

  • Related