How to update a variable

Hey Folkz, I’m looking for an API to update variable!

In the docs, I could see API to createVariable, createVariableCollection and several APIs to getting a variable, but how could I update a variable of a particular collection and mode?

I’ve tried the following code, but no luck with it

let variable = figma.variables.getVariableById("VariableID:104:28");
variable.valuesByMode['104:0'] = {r: 0, g: 0, b:0};

Thanks in advance!

Hey Mohan! From the code you’ve provided, it seems you’re trying to update the value of a variable by directly modifying its properties. However, the Figma plugin API is often more restrictive than regular JavaScript objects, and direct property modifications might not work as expected.

Here’s a step-by-step guide to update a variable:

  1. Get the Variable: You’ve already done this with the getVariableById method.
  2. Update the Variable: Instead of directly modifying the valuesByMode property, you might need to use a specific method to update the variable. The documentation you provided doesn’t seem to have a direct method for updating variables, but there are a few workarounds you can try:
  • Delete and Recreate: One way to “update” a variable is to delete the old one and create a new one with the updated values. This might not be the most efficient way, but it’s a workaround if no direct update method is available.
  • Check for Other Methods: The documentation might have other methods related to updating properties of design elements. Look for methods that might not be directly named “updateVariable” but could serve the purpose.
  1. Save or Commit Changes: After making changes, ensure that you’re saving or committing them. Some APIs require explicit calls to save changes made to objects.

Here’s a potential workaround using the delete and recreate method:

// Get the variable
let variable = figma.variables.getVariableById("VariableID:104:28");

// Store necessary properties
let collectionId = variable.collectionId;
let name =;
let description = variable.description;

// Delete the old variable

// Create a new variable with updated values
let newValuesByMode = {...variable.valuesByMode, '104:0': {r: 0, g: 0, b:0}};
figma.variables.createVariable(collectionId, name, description, newValuesByMode);

Use the setValueForMode method.

1 Like

Many thanks :blush:

@tank666 how to set the alpha value to the variable?

// this works fine
colorVariable.setValueForMode(lightModeId, {r: 0, g: 0, b: 0})

// but not this
colorVariable.setValueForMode(lightModeId, {r: 0, g: 0, b: 0, a: 0.5})

This should work.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.