Hi, I’m trying to load a font to use in a simple text box, but keep getting this error:
Cannot write to node with unloaded font “Roboto Regular”. Please call figma.loadFontAsync({ family: “Roboto”, style: “Regular” }) and await the returned promise first.
This is my code:
async function createNewTextStyle() {
// Style does not yet exist, so create it
const newStyle = figma.createTextStyle();
// the new text style is preloaded with Roboto, so we need to load that
await figma.loadFontAsync(newStyle.fontName);
// This is the font i want to set my text style to.
// it seems that this promise never resolves (or errors).
await figma.loadFontAsync({
family: 'Roboto',
style: 'Regular',
});
// Set the properties of the text style
newStyle.fontName = {
family: 'Roboto',
style: 'Regular',
};
}
createNewTextStyle();
I’m pretty new to JavaScript so I’m sure I’ve done something wrong, would love some help on this.
This function looks good to me (but can’t test now). Which line are you getting this error at? It seems like it doesn’t come from this function at all, as “writing to node” implies you are changing characters on the text element on canvas. Also I’m pretty sure you don’t need to load the default font of the style to change it, only the new font needs to be loaded.
Right okay I think that makes sense since I don’t think it’s coming from the function. Why would the error occur when I try to change characters on the text element. For reference this is where I call the text element.
You don’t load fonts at all in this piece of code, so this would explain the error (unless you have font loading code before it somewhere of course). You need to await for the fonts loading function to finish and then you can change the characters.
No. Just like you are awaiting for fonts to load (await figma.loadFontAsync), you need to await for the createNewTextStyle function to finish. Note that for that to work, it needs to be called inside the async function, not in the global scope since await only works inside async functions (but if you are using TypeScript, it should warn you about that).
Also if you removed the default font loading like I advised, you need to bring it back somewhere since you are not applying the style you just created and loaded the font for to the text you are modifying. So you can even drop that function completely and just load the default font before setting the characters to the text.