I'm attempting to remove spaces from a string in typescript, and one of the variables throws a big error when I refresh the page or load it fresh from the url, not when I load it from another page on my site. art.title is undefined, so I need to wait for the page to load before running the replace code.
I tried this code to define the variable I want only when it's ready, but I can't use that variable if it's defined within the conditional.
Here's the code I tried for defining the titleString variable I want:
function titleNoWhiteSpace() {
if (typeof art.title != 'undefined') {
const tempTitle = art.title.replace(/\s+/g, '');
return tempTitle;
} else {
setTimeout(titleNoWhiteSpace, 300);
}
}
const titleString = titleNoWhiteSpace();
But when I try to use titleString later, I get the following error because the variable isn't defined yet!
"Argument of type '{ titleString: string | undefined; }' is not assignable to parameter of type 'string'"
Here's the error that the code throws if I just try to replace whitespace in art.title directly:
"Uncaught TypeError: Cannot read properties of undefined (reading 'replace')"
Art types are declared here:
export interface Art {
uri: string | undefined;
mint: string | undefined;
link: string;
title: string;
artist: string;
seller_fee_basis_points?: number;
creators?: Artist[];
type: ArtType;
edition?: number;
supply?: number;
maxSupply?: number;
}
The function titleNoWhiteSpace as you've written it doesn't wait for the title to become defined the way I think you're hoping it waits.
The function always returns a result immediately (as do all JavaScript functions), either returning the de-spaced title, or undefined. At some point the de-spaced title will be generated, but the result will just be a fleeting un-stored value happening after you've gotten the undefined value you don't want.
The only way to get the kind of wait-until-the-title-is-defined effect you want it to use a Promise or a callback function. I can't be more specific without seeing the context where the title text is ultimately supposed to be used.