Rendering issue with multi-state box elements

Hello fellow developers, how are you?

I’m experiencing a rendering issue with the multi-state box element. Essentially, there’s an asynchronous function loading, and after it loads, it interacts with the multi-state element and changes it based on the type of data returned. So far, everything is working well; it correctly changes the state. However, the text elements placed just below do not render on the frontend, even though the console shows that all the elements have been loaded into the function. I managed to work around this by adding a 2-second timeout, but I still believe it’s not the most correct way to handle this. Does anyone have any ideas that could help me solve the problem?
Note: English is not my native language, so I apologize for any errors in the text.
Note 2: The function loads right at the beginning of the page load.
I’ll try to provide some context for the code below…

the code:

async function loadData() {
  // the big data loagind function
}


async function load() {
  const data = await loadData();

  fillMultiStateBoxWithLoadData(data);
}

function fillMultiStateBoxWithLoadData(data) {
  // handle diferent type in object
  if (data.type === 'type1') {
    // change to state 'type1'
    $w('#statebox').changeState('type1');
    fillDataType1(data);
  } else {
    // change to state 'type2'
    $w('#statebox').changeState('type2');
    fillDataType2(data);
  }
}

function fillDataType1(data) {
  // sometimes doens't load in frontend
  $w('#element').text = `${$w('#element').text} ${data.text}`
}

function fillDataType2(data) {
  // sometimes doens't load in frontend
  $w('#element2').text = `${$w('#element2').text} ${data.text}`
}

// load page
$w.onReady(() => {
  load();
});

Since changeState() is asynchronous what might help is to do something like the below instead:

$w("#statebox").changeState('type1')
  .then( (newState) => {
    fillDataType1(data);
  } );

or alternatively, change fillMultiStateBoxWithLoadData to an async function and then await $w('#statebox').changeState('type1');.

Obviously do this for both type1 and type2.

It’s possible that the fillData functions are being called before changeState() is done and this is creating the issue.

Thank you man! You are completely correct and it helped me a lot. I changed the code following your instructions and it solved the problem.

1 Like