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

Time:04-20

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: '[email protected]', 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

CodePudding user response:

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

CodePudding user response:

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

interface BackendData {
  _id: number;
}
  • Related