Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle date object in API response

I have a c# .net 8 backend (later known as BE) to provide my react typescript frontend (FE) with data.

I use RTK Query to fetch the data but I just ran into trouble when assuming that the Date object I got from BE was infact a Date object.

Class in BE:

public class Action
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime? StartDate { get; set; }
}

Type in FE:

export interface Action {
  id: number;
  name: string;
  startDate: Date;
}

RTK Query endpoint:

actionById: builder.query<Action, number>({
   query: (id: number) => ({
       url: `${BASE_URL}/v1/Action/${id}`
       method: 'GET',
   }),
}),

Response from BE is obiviously a JSON String but I thought the conversion to Date object were made automatically. It was not. Everything worked fine until I tried to compare it with another date which failed.

So question is, how do I solve this in the best way?

I could change the type in FE to be startDate: string; to avoid the confusion, but is there a better way?

like image 317
Mangs Avatar asked Dec 07 '25 16:12

Mangs


1 Answers

I would suggest to use transformResponse in order to transform response data as needed. Maybe something like this:

actionById: builder.query<Action, number>({
  query: (id: number) => `${BASE_URL}/v1/Action/${id}`,
  transformResponse: (response) => ({ ...response, startDate: new Date(response.startDate) }),
}),
like image 131
pzaenger Avatar answered Dec 09 '25 17:12

pzaenger