Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda