I'm trying to make a react-query mutation (using axios, but I get the same behavior if I switch to the fetch API).
I set it up like this.
const mutation = useMutation(
() => {
axios.post("http://swapi.dev/api/foobar", {});
},
{
onSuccess: () => {
console.log("success");
},
onError: () => {
console.log("error");
},
}
);
The URL can be anything that fails. I've tried it on the real API I'm using, returning both 500 and 404 errors.
I fire the mutation as follows.
mutation.mutate();
Every time I get "success" displayed in the console. The onError handler never fires. The calls return the expected errors when viewed in Chrome's network tab (and display console errors).
I'm using react-query 3.3.6 and axios 0.21.1 (both the latest release versions).
Can anyone point me in the right direction?
useMutation first parameter expects a function which returns a promise. This is known as the mutation function. Instead of returning a promise, you're returning a void. You'll want to either use async/await or return the promise from axios.
const mutation = useMutation(
() => {
return axios.post('http://swapi.dev/api/foobar', {})
},
{
onSuccess: () => {
console.log('success')
},
onError: () => {
console.log('error')
}
}
)
Related
This is what I tried so far.
Let's say result is a StreamSubscription.
This is my flutter file
try {
result.listen(
(event) async {
// This converts the JSON data
final news = NewsModel.fromJSON(jsonDecode(event));
// This saves the data to local database
await localDataSource.saveNews([news]);
},
onError: (e) {
debugPrint('$e');
},
);
} catch (e) {
debugPrint('$e');
}
this is my flutter test since I want to test if method localDataSource.saveNews() fails
await newsRepository.subscribe(); calls the try catch above
controller is a StreamController to add new data to the stream
news is a dummy data, it doesn't matter because whatever the localDataSource do it will throw a LocalDBException
also I am using Mockito https://pub.dev/packages/mockito to mock the localDataSource above
test(
'should handle fail save news method',
() async {
// arrange
when(mockLocalDataSource.saveNews(any)).thenThrow(LocalDBException());
// act
await newsRepository.subscribe();
controller.add(news)
// assert
},
);
As you can see I don't have any condition to pass the flutter test, but that's beyond the point as this flutter test already breaks the stream even if I have a onError on my listener.
if I use controller.addError(LocalDBException()) the onError works, but if I deliberately throw an exception from the method localDataSource.saveNews() it breaks the stream.
Given this context I want to know 2 things:
I want to know how to handle the error inside the onData of StreamSubscription, if a method / function throw an exception, as it ignores the onError if a method / function throw an exception inside the listener.
Is adding an error through addError() function the same as throwing an exception inside the stream?
I have a section of an app dedicated to deleting all of a user's data. Firebase auth requires a user to reathenticate before deleting its data, so im trying the following function:
onPressed: () async {
try {
AuthCredential
credential =
EmailAuthProvider
.credential(
email: '',
password: '',
);
_firebaseAuth.currentUser!
.reauthenticateWithCredential(
credential);
BlocProvider.of<
ProfileBloc>(
context)
.add(DeleteProfile(
user: user,
stingrays: stingrayState
.stingrays,
));
Navigator.pushNamed(
context, '/wrapper/');
} on Exception catch (e) {
print(e.toString());
}
},
In this case, setting the email and password as '' should throw an error. My current idea is that the function should run until reauthenciation is called, then an error should be thrown and it does not finish the deleting process. However, it currently does not operate like this, instead running through the entire function. Any idea how to fix this conditional reauthentication method?
Thank you!
You can just call return whenever you want your code to stop and it will.
So after your authentication do this.
_firebaseAuth.currentUser!.reauthenticateWithCredential(credential);
return;
Also reauthenticateWithCredential() is a Future<void> so you have to await it:
return await _firebaseAuth.currentUser!.reauthenticateWithCredential(credential);
I have this method which gets a suggested place through the Google Places API based on the user input.
void getSuggestion(String input) async {
var googlePlace = GooglePlace(AppConstants.APIBASE_GOOGLEMAPS_KEY);
var result = await googlePlace.queryAutocomplete.get(input);
setState(() {
_placeList = result!.predictions!;
});
}
_placeList is filled properly, but it does not get updated instantly, I have to hot reload to see the changes whenever I change the query value in my TextController:
TextField(
onSubmitted: (value) {
setState(() {
getSuggestion(value);
showDialog(
context: context,
builder: ((context) {
return Card(
child: ListTile(
title: Text(_placeList[0].description),
),
);
}));
});
},
For example, if I search for "Miami" I get the recommendation on my listTile, but if I change it to "Madrid" it still appears "Miami" and I have to reload screen to see the change.
I do not understand because I am setting the state in my method.
getSuggestion is an asynchronous function. In other words, in the following code snippet:
getSuggestion(value);
showDialog(
context: context,
...
After invoking getSuggestion, it does not wait the function to finish before showing the dialog. In other words, when the dialog is shown, maybe the previous function hasn't completed yet, so that _placeList is not updated yet.
Firstly, it is a better idea to get rid of setState within getSuggestion as it is redundant to do it twice.
Secondly, in the onSubmitted lambda, make the anonymous function async (onSubmitted: (value) async { ...), then wait for getSuggestion to finish by await getSuggestion() (do not await inside setState). At this point, _placeList is updated, and you can invoke setState now, things should rebuild properly if there are no other errors.
I'm having an issue with React Query where if a user presses a button too fast, triggering a mutation, the correct value flashes and changes on the screen as the API calls are returned, even when attempting to cancel them. I notice this problem also happens in the official React Query example for optimistic updates. Here's a video I took of the problem happening there.
export const useIncreaseCount = () => {
const queryClient = useQueryClient()
return useMutation(
() => {
const cart = queryClient.getQueryData('cart') as Cart
return setCart(cart)
},
{
onMutate: async (cartItemId: string) => {
await queryClient.cancelQueries('cart')
const previousCart = queryClient.getQueryData('cart') as Cart
queryClient.setQueryData(
'cart',
increaseCount(previousCart, cartItemId)
)
return { previousCart }
},
onError: (error, _cartItem, context) => {
console.log('error mutating cart', error)
if (!context) return
queryClient.setQueryData('cart', context.previousCart)
},
onSuccess: () => {
queryClient.invalidateQueries('cart')
},
}
)
}
I'm thinking of debouncing the call to use useIncreaseCount, but then onMutate will get debounced, and I don't want that. Ideally just the API call would be debounced. Is there a built in way in React Query to do this?
The problem come from the fact that every onSuccess callback calls queryClient.invalidateQueries, even though a different invocation of the mutation is still running. It's the responsibility of the user code to not do that. I see two ways:
One thing we are doing sometimes is to track the amount of ongoing mutations with a ref (increment in onMutate, decrement in onSettled), then only call queryClient.invalidateQueries if the counter is zero.
assigning mutationKeys and using !queryClient.isMutating(key) should also work.
Lets say that in Dart/Flutter you have the following code:
void myOperation() {
// could be anything
print('you didn't cancel me!');
}
Notice that the operation itself is not asynchronous and is void -- does not return anything.
We want it to execute at some point in the future, but we also want to be able to cancel it (because a new operation has been requested that supersedes it).
I've started by doing this:
Future.delayed(Duration(seconds: 2), myOperation())
... but this is not cancellable.
How exactly could you schedule that "operation," but also make it cancelable?
I'm thinking... we could modify the code like so:
Future.delayed(Duration(seconds: 2), () {
if (youStillWantThisToExecute) {
print('you didn't cancel me!');
}
});
But that's not really very good because it depends on a "global" boolean... and so if the boolean gets flipped to false, no operations will complete, even the most recently requested, which is the one we want to complete.
It would be nicer if there were a way to create any number of instances of the operation and cancel them on an individual basis... or to have a unique id assigned to each operation, and then instead of having a boolean control whether or not to execute... to have a "mostRecentId" int or something which is checked prior to execution.
Anyways...
CancelableOperation seemed promising just from its name.
So, I looked at its documentation:
CancelableOperation.fromFuture(Future inner, {FutureOr onCancel()})
Creates a CancelableOperation wrapping inner. [...] factory
But honestly that just makes my poor head hurt oh so much.
I've consulted other articles, questions, and answers, but they are all part of some specific (and complex) context and there isn't a dirt simple example anywhere to be found.
Is there a way to make a delayed future cancellable by wrapping it in some other class?
Can someone more experienced please provide at least one simple, complete, verified example that compiles in DartPad?
Thanks.
Use Timer:
var t = Timer(Duration(seconds: 400), () async {
client.close(force: true);
});
...
t.cancel();
Using CancalableOperation will not stop print('hello'); from executing even if you cancel. What it does is canceling(discarding) the result(void in your case). I will give you 2 examples using CancalableOperation and CancalableFuture.
CancelableOperation example
final delayedFuture = Future.delayed(
Duration(seconds: 2),
() {
return 'hello';
},
);
final cancellableOperation = CancelableOperation.fromFuture(
delayedFuture,
onCancel: () => {print('onCancel')},
);
cancellableOperation.value.then((value) => {
// Handle the future completion here
print('then: $value'),
});
cancellableOperation.value.whenComplete(() => {
print('onDone'),
});
cancellableOperation.cancel(); // <- commment this if you want to complete
CancelableFuture example
final delayedFuture = ...;
final cancalableFuture = CancelableFuture<String>(
future: delayedFuture,
onComplete: (result) {
// Use the result from the future to do stuff
print(result);
},
);
cancalableFuture.cancel(); // <- commment this if you want to complete
And the CancelableFuture implementation
class CancelableFuture<T> {
bool _cancelled = false;
CancelableFuture({
#required Future<dynamic> future,
#required void Function(T) onComplete,
}) {
future.then((value) {
if (!_cancelled) onComplete(value);
});
}
void cancel() {
_cancelled = true;
}
}
You cannot cancel an existing Future. If you do:
Future.delayed(
Duration(seconds: 2),
() {
print('hello');
},
);
as long as the process runs (and is processing its event queue) for at least 2 seconds, the Future eventually will execute and print 'hello'.
At best you can cause one of the Future's completion callbacks to fire prematurely so that callers can treat the operation as cancelled or failed, which is what CancelableOperation, et al. do.
Edit:
Based on your updated question, which now asks specifically about delayed Futures, you instead should consider using a Timer, which is cancelable. (However, unlike a Future, callers cannot directly wait on a Timer. If that matters to you, you would need to create a Completer, have callers wait on the Completer's Future, and let the Timer's callback complete it.)