Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Usestate not updating value on first render

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!