I'm working on an application where authenticated user data mostly comes from an API.
Performance is significantly better since I'm using the API cache. Before, to be sure to have up-to-date information, I used '#cache' => ['max-age' => 0,]
but it's really not ideal.
I have a question, however, about the custom block cache for authenticated users.
If I add user context and tag it works fine for authenticated users.
return [
'#theme' => 'lorem',
'#datas' => $datas,
'#cache' => [
'contexts' => ['user'],
'tags' => ['user:' . \Drupal::currentUser()->id(), 'lorem_custom_block:' . \Drupal::currentUser()->id(), 'lorem_custom_block_user:' . \Drupal::currentUser()->id()]
],
];
But one of my clients to test the application uses his Drupal account (therefore always the same Drupal user id) and changes a value of a custom field in his profile (an external id which is used to retrieve information with the API). In this case, I use a hook_user_presave
and invalidate the custom block cache like this :
Cache::invalidateTags(['lorem_custom_block_user:' . $user_id]);
In this case, it does not work. The information displayed in the block is not up to date. I have to remove the context user on the block and it works.
return [
'#theme' => 'lorem',
'#datas' => $datas,
'#cache' => [
'tags' => ['user:' . \Drupal::currentUser()->id(), 'lorem_custom_block:' . \Drupal::currentUser()->id(), 'lorem_custom_block_user:' . \Drupal::currentUser()->id()]
],
];
Is this the normal behavior? it's as if there is a conflict between the context and the tag.
I thought invalidating the tag would be enough.
Maybe it doesn't make sense to use a context in my case. Can you give me your opinion?