ive got this function that calls an API
interface getEventsPropsShape {
eventId?: string;
accountId?: string;
eventsStartAfter?: string;
}
const getEvents = async ({
eventId,
accountId,
eventsStartAfter,
}: getEventsPropsShape): Promise<void> => {
let apiUrl: string = '/v1/developer/events?limit=25&ascending=false';
eventId !== undefined ?? (apiUrl = `&eventId=${eventId}`);
accountId !== undefined ?? (apiUrl = `&accountId=${accountId}`);
eventsStartAfter !== undefined ??
(apiUrl = `&eventsStartAfter=${eventsStartAfter}`);
const response = await get(apiUrl);
This works because it doesn't add eventId
to apiUrl
let apiUrl: string = '/v1/developer/events?limit=25&ascending=false';
eventId !== undefined ?? (apiUrl = `&eventId=${eventId}`);
but this doesn't work because it ads eventId = undefined
to the apiUrl
let apiUrl: string = '/v1/developer/events?limit=25&ascending=false';
eventId ?? (apiUrl = `&eventId=${eventId}`);
ultimately I'm looking to remove the if blocks from
if (eventId) apiUrl = `&eventId=${eventId}`;
if (accountId) apiUrl = `&accountId=${accountId}`;
if (eventsStartAfter) apiUrl = `&eventsStartAfter=${eventsStartAfter}`;
CodePudding user response:
Change ??
to &&
. Example:
let eventId = undefined;
let apiUrl = '/v1/developer/events?limit=25&ascending=false';
eventId && (apiUrl = `&eventId=${eventId}`);
console.log(apiUrl);
eventId = 'foo';
apiUrl = '/v1/developer/events?limit=25&ascending=false';
eventId && (apiUrl = `&eventId=${eventId}`);
console.log(apiUrl);
Or:
let eventId = null;
let apiUrl = '/v1/developer/events?limit=25&ascending=false';
eventId !== undefined && (apiUrl = `&eventId=${eventId}`);
console.log(apiUrl);
eventId = 'foo';
apiUrl = '/v1/developer/events?limit=25&ascending=false';
eventId !== undefined && (apiUrl = `&eventId=${eventId}`);
console.log(apiUrl);