How to properly update state in a generator-based redirect loop?