If you run that chunk of code from the preceding section as an anonymous user, you'll note that the entry gets created in the database with a session ID, as expected. However, upon the next request, if you try to retrieve the value by key, you won't find it. That is because anonymous users do not necessarily have a session started. This means a new session ID is created for each request. So, how can we solve this?
The first time you start the process or flow in which you need to interact with the private tempstore, check yourself whether the current user is anonymous. If they are, dump a variable into the $_SESSION super global in order to keep the session. Otherwise, it gets erased because there is no data. So, do something like this:
if (\Drupal::currentUser()->isAnonymous()) {
$_SESSION['hold_session'] = true;
}
If you do this, the session gets preserved, and with the next request, the same user will have the same session ID and will be able to access the entries that belong to them. Of course, if you can, inject the current_user service instead of calling it by the static shorthand.