How to list elements of an object in React Typescript?

Viewed 32

I want to list the elements of the objects in my Typescript react project. If I make in this way:

const data = Dependencies.backend.getList(caseDetailUrl + this.props.id);
data.then(res => {
      console.log(res)
    })

The output is but when I refresh page it prints 2 times I don't know why:

{
    "id": "669f83",
    "creation_date": "2022-01-13 10:33:06.046652+01:00",
    "case_type": "Sum",
    "current_stage": "",
    "last_change_date": "2022-01-14 14:35:17.563449+01:00",
    "status": 1,
}

I want to display these info but I can't.

Firstly, I try:

let case_value
data.then(res => {
      case_value.push(res)
    })

and It shows an error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')

And when I use .map instead of .then

Property 'map' does not exist on type 'Promise<unknown[] | undefined>'.ts(2339)

Updated code

   const data = Dependencies.backend.getList(caseDetailUrl + this.props.id);
    type resultType = Record<number, string>
    let case_value : Array<resultType>
    data.then(res => {
      case_value.push(res)
    })

My whole code is:

import React from "react";
import { Dependencies } from "../../../shared/utils/dependencies";
import { caseDetailUrl } from "../../constants/backend-constants";

interface CaseDetailProps {
  id: string,
}

class CaseDetail extends React.Component<CaseDetailProps> {

  render() {
    const data = Dependencies.backend.getList(caseDetailUrl + this.props.id);
    let case_value
    data.then(res => {
      case_value.push(res)
    })
    return (
      <div className="caseDetail">
        <h1>Hi!</h1>
        <h3>{this.props.id}</h3>
      </div>
    );
  }
}

export default CaseDetail;

How can I display it?

1 Answers

The error is certain as the type for case_value variable is not defined. Hence, you cannot read properties of undefined variable.

 let case_value  //here the case_value is just declared with no type. 
    data.then(res => {
      case_value.push(res)
    })

How can compiler know that there is a method called push available on it. Therfore, first define the type of it and then use its available properties/methods.

 let case_value : Array<provide-type-of-res-here>
    data.then(res => {
      case_value.push(res)
    })

For ex: if res looks like this.

res = {
1 : "hello"
2 : "thanks"
}

its type can be like :

type resultType = {
1 : string,
2 : string,
}

or

type resultType = Record<number, string>

and then pass this type to Array<{here}>

 let case_value : Array<resultType>
    data.then(res => {
      case_value.push(res)
    })
Related