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?
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) }),
}),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With