简体   繁体   中英

Property '_id' does not exist on type '{}[]'

I'm c native and I'm studying JS, TS, ReactJs. I created an application for study purposes, I am sending from the backend a package like:

{_id: '624d9476a390104449255c45', email: 'JohnSpecial@gmail.com', username: 'JohnSpecial', userpass: '12345', __v: 0}. 

In my frontend I use react and ts. The app is very simple: I use fetch to make requests to the backend. This is my code:

import { useEffect, useState } from 'react'

export const App = () => {
  const [backendData, setbackendData] = useState([{}])

  useEffect(() => {
    fetch('/readData/12345')
      .then((response) => response.json())
      .then((data) => {
        console.log('Data Received ' + JSON.stringify(data[0]))
        var myArr = JSON.parse(JSON.stringify(data[0]))
        console.log(myArr)
        setbackendData(myArr)
      })
  }, [])

  return (
    <div className="App">
      Mongodb React Typescript - Send Data
      <p></p>
      {typeof backendData._id === 'undefined' ? <p>Loading...</p> : backendData._id}
    </div>
  )
}

I was using react and javascript and it was working. When I started using TS it started to look like this error message: Property '_id' does not exist on type '{}[]'.

How can I show this JSON on my browser?

Thanks

You'll need to tell typescript what type of data will be stored in the useState hook.

import { useEffect, useState } from 'react'

interface BackendData {
  _id: number;
}

export const App = () => {
  const [backendData, setbackendData] = useState<BackendData | null>(null)

  useEffect(() => {
    fetch('/readData/12345')
      .then((response) => response.json())
      .then((data) => {
        setbackendData(data[0] as BackendData)
      })
  }, [])

  return (
    <div className="App">
      Mongodb React Typescript - Send Data
      <p></p>
      {backendData ? backendData._id : <p>Loading...</p>}
    </div>
  )
}

playground

Your backendData has type {}[] . You need to properly type it. Example:

interface BackendData {
  _id: number;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM