Reputation: 33
What I'm trying to do is when I log in , it takes the token from the API and update it to the riverpod state provider so the user Future provider sends a get request to the API and get the data from the API and returns it , What my API does is whenever there's a token that means user is authenticated otherwise return a Guest user so everytime I login it returns me as a Guest user because the future provider doesn't read the token state provider
Future<LoginResponse?> logintoDjango() async {
...
if (response.statusCode == 200) {
String userToken = responseJson['data']['token'];
await CacheHelper.setString("token", userToken);
ref.read(userTokenProvider.notifier).update((state) => userToken); //Here how it updates
...
}
''
String getToken() {
final token = ref.watch(userTokenProvider);
if (token.isNotEmpty) {
return token;
}
return CacheHelper.getString("token") ?? '';
}
final userTokenProvider = StateProvider<String>((ref) => '');
final FutureProvider<UserData> userDataProvider =
FutureProvider<UserData>((ref) async {
print("Step1");
...
final token = ref.read(authHelperProvider).getToken(); //THERE
...
final response = await client.get(
url,
headers: token != '' ? {'Authorization': 'Token ${token}'} : {},
);
return UserData.fromJson(json.decode(response.body));
});
I tried calling
final token = ref.read(authHelperProvider).getToken();
on a different screen in the widget build and It returns the token correctly but it doesn't return it to the future provider
CacheHelper
is my Shared preferences helper class
Upvotes: 0
Views: 1367
Reputation: 33
Fixed my question after reading the documentation, I've found that It should be ref.watch
instead of ref.read
and it worked , Thank you so much
Upvotes: 2