Changing the key

In this lesson you will learn how to control the code without editing it. You already have enough functionality in the code to start targeting, but you're going to add code that makes it easier to test that targeting: dynamically changing the key in the user object.

Adding a dialog box

Right now, changing the key attribute requires editing the code. You need a way to easily change the key see how it affects the flag evaluation. To do this, you can add a debug trick displaying a dialog box that lets you enter a new key when you click on the "Toggle Runner" header.

To add the dialog box:

  1. Add this code at the bottom of js/app.js:

    // This `updateUser()` function ask the user for a new key,
    // then changes the user object.
    function updateUser() {
      let newKey = window.prompt("Enter a new user key", lduser.key);
      if (newKey !== null && newKey !== "") {
        lduser.key = newKey;
        ldclient.identify(lduser, null);
      }
    }
    
    // Call the updateUser() functon when the user clicks on the header
    document.getElementById("heading").addEventListener("click", updateUser);
    
  2. Click the "Run" button in Replit.

  3. Click the "Toggle Runner" header. A window appears pre-filled with the starting key user123.

The key is reset to that value every time you restart the app, but you can change the key without restarting by entering a new key in the window.