0

I am trying to update a state of an undefined object in Typescript.

This is the state I want to update:

const [newEvents, setNewEvents] = useState<DataType[] | undefined>(undefined)
type DataType = {
      Area: string;
      eventDate: string;
      eventId: string;
      type: string;
      geolocation: string;
      picUrls: string[]; 
    };

useEffect(() => {
      _getNewEvents()
    }, [])


async function _getNewEvents() {
      const result = await getEvents('hovedstaden');
      var final_result = result as DataType[];
      console.log(final_result)
      setNewEvents(final_result)
      console.log(newEvents)
  }

return (...

The request returns the following json object:

[{
 Area: "hovedstaden",
 eventDate: "2022-05-05T21:00:00.000Z",
 eventId: "RasmusSeebachVega",
 geolocation: "55.67594,12.56553",
 picUrls: ["IMAGE_03","IMAGE_04"],
 type: "koncert",
  },
 {
 Area: "hovedstaden",
 eventDate: "2022-05-15T20:00:00.000Z",
 eventId: "JonahBlacksmithVega",
 geolocation: "55.676098:12.568337",
 picUrls: ["IMAGE_01, IMAGE_02"],
 type: "koncert",
 }]

And the console.log outputs are as follows:

Array [
  Object {
    "Area": "hovedstaden",
    "eventDate": "2022-05-05T21:00:00.000Z",
    "eventId": "RasmusSeebachVega",
    "geolocation": "55.67594,12.56553",
    "picUrls": Array [
      "IMAGE_03",
      "IMAGE_04",
    ],
    "type": "koncert",
  },
  Object {
    "Area": "hovedstaden",
    "eventDate": "2022-05-15T20:00:00.000Z",
    "eventId": "JonahBlacksmithVega",
    "geolocation": "55.676098:12.568337",
    "picUrls": Array [
      "IMAGE_01, IMAGE_02",
    ],
    "type": "koncert",
  },
]
undefined

The annoying part is that the second console.log is returning undefined, which means the last two lines of code do not update the state. Can someone point out, what I am doing wrong?

Bonus question: Is it necessary to create a DataType to update state values from json objects? I mean what if I was not sure about which attributes the object would contain?

nicklasc93
  • 67
  • 5

0 Answers0