Comments (4)
Yes that is exactly how mutations work, you are not expected to have the information right away, you pass the dynamic data to the myMutation.mutate(payload)
function.
For rapini, you take the mutations from the intiialize, so
const { mutations } = initialize(axios)
// inside component
const myMutation = mutations.useMyMutation()
const onFormSubmit = () => {
myMutation.mutate({ my dynamic data goes here })
}
hope that helps. The react query mutation docs has more details on that
from rapini.
that's helpful - thank you
but still not clear how to do the straightforward - checking of errors - and if it is an error - show message.
some historic boilerplate code I've used in the past - where ICredential is username / password
async function loginUserClearCookies(credentials: ICredential) {
console.error("WARNING - deleting existing session details if any...")
const keys = ['tokenExpiredCount', 'token', 'user'];
await AsyncStorage.multiRemove(keys);
const hasInternet = checkConnectivity();
if (!hasInternet) {
setErrorMessage('No internet detected...');
SnackbarHandler.errorToast("No internet...");
return
}
setPreload(true);
SnackbarHandler.normalToast("Authorising...");
/// HERE I CAN CALL MUTATE - but am I expecting this inside a try / catch ? and then handling error?
NocApi.post('/logon', credentials)
.then(response => {
if (response.data) {
setErrorMessage('');
const token = `wa=wsignin1.0&wresult=${encodeURIComponent(
response.data
)}`;
// console.log('token', token);
if (token) {
Promise.all([
setUser(credentials),
postTokenForCookie(token), // this will transition ui isAuthenticated -> true -> logged in > and kick off fetchAll once we get cookie
setToken(token),
])
.then(async (res) => {
setPreload(false);
})
.catch(err => {
console.error('err', err);
Analytics.trackEvent(err.message);
SnackbarHandler.errorToast("🔥 LOGIN FAILED!!!");
setPreload(false);
});
}
}
})
.catch(error => {
setPreload(false);
let err = error as AxiosError
Analytics.trackEvent(err.message)
if (err.message == "Network Error") {
console.error("We cancelled the request!!");
SnackbarHandler.errorToast(err.message);
return;
}
SnackbarHandler.errorToast('Email or Password not correct');
});
}
UPDATE
this is some boiler plate code that I'm wrapping around to the typescript librrary / axios spat out by swagger-codegen-cli-3.0.41.jar
java -Xmx1024m -jar swagger-codegen-cli-3.0.41.jar generate -i openapi.yaml -l typescript-axios -o generate --additional-properties npmName=@flow,npmVersion=0.0.59,private=false
const handleLogin = async () => {
setLoading(true);
setError('');
try {
var model:UserLoginModel = {}
model.userName = username
model.password = password
//usePostAuth(model);
let result = UsersApiFp().postAuth(model);
console.log("result:",result);
setLoading(false);
} catch (e) {
setLoading(false);
setError('Invalid username or password');
}
};
from rapini.
@cn-johndpope this seems like a general react query mutation question, there are a lot of docs about how to use it here https://tanstack.com/query/v4/docs/react/guides/mutations . You don't need separate states for loading or errors, don't need a try/catch either, it's all built-in to the hook
from rapini.
ok touche - this example is perfect. Would be better to replace the other one you have which falls short of showcasing finer details.
I can see a path forward now - thanks
I hit a snag using the tanstak v4 - I'll raise separate ticket.
function App() {
const mutation = useMutation({
mutationFn: (newTodo) => {
return axios.post('/todos', newTodo)
},
})
return (
<div>
{mutation.isLoading ? (
'Adding todo...'
) : (
<>
{mutation.isError ? (
<div>An error occurred: {mutation.error.message}</div>
) : null}
{mutation.isSuccess ? <div>Todo added!</div> : null}
<button
onClick={() => {
mutation.mutate({ id: new Date(), title: 'Do Laundry' })
}}
>
Create Todo
</button>
</>
)}
</div>
)
}
from rapini.
Related Issues (20)
- Export union types as objects HOT 1
- Feature request: optionally generate MSW mocks too HOT 1
- Anyof doesn't generate correct response HOT 2
- Use `npx` instead of `npm install -g` HOT 1
- Typescript support HOT 3
- Ability to change the way array param are sendt HOT 1
- react-query cache HOT 1
- https://orval.dev/ HOT 9
- error trying to run HOT 6
- Does Rapini generate code which is able to handle files download where the content-type=application/octet-stream? HOT 5
- The promise rejected with the reason "Missing "operationId" from "get" request with pattern /api/configuration/{orgId}/meterType".] HOT 2
- TypeError: Cannot read properties of undefined (reading 'split') HOT 1
- clarity on what is needed to correctly create react hook HOT 2
- Clarification on how to use onSuccess / onError with mutation HOT 1
- Evaluation report (with Vue 3 + Vue Query) HOT 2
- (Suggestion) - Conditional support for UseInfiniteQuery HOT 1
- Can rapini generate code with responseType: 'blob' for file GET requests? HOT 1
- Does Rapini support React Query 5? HOT 1
- Generated code incompatible from 5.14.6 to 5.17.9 of @tanstack/react-query HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from rapini.