Read riverpod stream value in useEffect

Issue

I want to read the first value from a list stream in useEffect to select the first value in the list returned. How do I do this differently.

Shows an error on restart.

I am using hooks_riverpod

    
    final _locations = useProvider(locationsProvider); // provides AsyncValue<List<FacilityLocation>> 
    final _selectedLocationID = useState('');

    useEffect(() {
      _locations.when(
        data: (locations) {
          final _location = locations[0];
          return _selectedLocationID.value = _location.locationID;
        },
        loading: null,
        error: (err, stack) => null,
      );
      return;
    }, []);

Solution

Why not create another provider for the first value in the list instead? You could also create an additional provider for the id of that first value in the list. Instead of messing around with all this logic in your build function.

class Facility {
  const Facility(this.id);

  final String id;
}

final locationsProvider =
    StreamProvider<List<Facility>>((_) => Stream.value([Facility('A'), Facility('B')]));

final firstLocation = FutureProvider<Facility>((ref) async {
  final locations = await ref.watch(locationsProvider.last);
  return locations.first;
});

// Can also do this as a FutureProvider, just wanted to add flavor.
final firstLocationId = Provider<String?>((ref) => ref.watch(firstLocation).data?.value.id);

Answered By – Alex Hartford

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.