DrupalSettings are not passing the values from block to js? I have been trying to pass the variables from block to jquery.

In Block.php,

return [
      '#theme' =&gt; 'block--exampleblock',
      '#value' =&gt; 'test',
      '#attached' =&gt; [
        'drupalSettings' =&gt; [
          'example' =&gt; [
            'data' =&gt; $data,
            'color'=&gt; $color,
          ],
        ],
        'library' =&gt; [
          'example/examplejs',
        ],
      ],
    ];


and I used the data and color values in js

drupalSettings.example.data; 
drupalSettings.example.color;


and belows are added the dependency in the library

dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings


After uninstalled and installed the modules, The variables have been passing from block to js. 

But After clearing cache or sometimes Its not working.

Its showing an issue like

Uncaught TypeError: Cannot read property 'data' of undefined
    at Object.attach (charts.js?v=1.x:10)
    at drupal.js?v=8.6.16:25
    at Array.forEach (&lt;anonymous&gt;)
    at Object.Drupal.attachBehaviors (drupal.js?v=8.6.16:22)
    at drupal.init.js?v=8.6.16:16
    at HTMLDocument.t (ready.min.js?v=1.0.8:4)


I am not able to fix this issue.

Can anyone help to solve this?
99 % sure it is the way your js file is set. as the above should work. for a test please do this: 

(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.testStuff = {
    attach: function (context) {
        alert('yes i am attached');
        console.log(drupalSettings);
        if (drupalSettings.example) {
           console.log(drupalSettings.example);
        }
    }
  };
})(jQuery, Drupal, drupalSettings);


if you don't see that in the log then try this ...

$build = [];
$build['stuff'] = [
  '#theme' =&gt; 'block--exampleblock',
  '#value' =&gt; 'test',
];
$build['#attached']['drupalSettings']['example'] =  [
        'data' =&gt; $data,
        'color'=&gt; $color,
];
$build['#attached']['library'][] = 'example/examplejs';
return $build;


remember to clear your cache too.