@apollo/react-hooks#useApolloClient JavaScript Examples
The following examples show how to use
@apollo/react-hooks#useApolloClient.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: apollo.js From mailmask with GNU Affero General Public License v3.0 | 6 votes |
useSafeMutation = (mutation, opts) => {
const client = useApolloClient()
const [ result, setResult ] = useState({})
const fn = useCallback(async args => {
setResult({
loading: true
})
let ret
let error
try {
ret = await client.mutate({
mutation,
...opts,
...args
})
} catch (err) {
error = err
}
if (!error) {
error = resolveError(ret)
}
if (error) {
ret = {
error: constructUserFriendlyError(error),
}
}
setResult(ret)
return ret
}, [ mutation, opts, client ])
return [ fn, result ]
}
Example #2
Source File: generalInfo.js From resumeker-fe with MIT License | 4 votes |
export default function GeneralInfo(props) {
const client = useApolloClient();
const [info, setInfo] = useState({
email: "",
firstName: "",
lastName: "",
});
//Instantiate useMutation Hook / Creates tuple with 1st var being actual
//call function, and 2nd destructured variable being return data and tracking
const [addDraft, { loading, error }] = useMutation(ADD_DRAFT_MUTATION, {
// refetchQueries: ["getDrafts"],
onCompleted(data) {
// console.log("cache\n", cache);
// need to refetch and update our getDrafts query
localStorage.setItem("draftID", data.addDraft);
},
});
const classes = useStyles();
const nextPage = (event) => {
event.preventDefault();
const name = info.firstName + " " + info.lastName;
//Calls addDraft Mutation only if component state
//is NOT empty
if (
info.firstName.length > 0 &&
info.lastName.length > 0 &&
info.email.length > 0
) {
//Apollo useMutation API call to send data to backend
addDraft({
variables: {
input: {
name: name,
email: info.email,
},
},
});
}
props.setActiveStep((prevActiveStep) => prevActiveStep + 1);
props.history.push("/form/education");
};
const onChange = (event) => {
setInfo({ ...info, [event.target.name]: event.target.value });
};
if (loading) return <div>loading : {loading}</div>;
if (error) return <div>{error}</div>;
return (
<div id="generalInfoForm">
<Grid container componet="main" className={classes.root}>
<CssBaseline />
<TipsLayout tips={Tip()} />
<Grid item xs={12} sm={8} md={9} component={Paper} elevation={6} square>
<MobileStepper
variant="progress"
steps={8}
position="static"
activeStep={props.activeStep}
className={classes.progress}
/>
<div className={classes.paper}>
<form className={classes.form}>
<GeneralInfoFormTemplate onChange={onChange} info={info} />
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
onClick={nextPage}
className={classes.submit}
>
Next
</Button>
</form>
</div>
</Grid>
</Grid>
</div>
);
}
Example #3
Source File: CompleteSignupForm.js From mailmask with GNU Affero General Public License v3.0 | 4 votes |
CompleteSignupForm = ({ className, onComplete }) => {
useEffect(() => {
trackEvent('signup', 'ViewFinalizeSignUpForm')
}, [])
const apolloClient = useApolloClient()
const [ termsAgreed, setTermsAgreed ] = useState(false)
const [ username, setUsername ] = useState('')
const [ isValid, setIsValid ] = useState(false)
const [ isAvailable, setIsAvailable ] = useState(false)
const [ checkingUsername, setCheckingUsername ] = useState(false)
const [ doRequest, result ] = useSafeMutation(CompleteSignupMutation)
const canSubmit = useMemo(() => isValid && isAvailable && termsAgreed, [ isValid, isAvailable, termsAgreed ])
const toggleTermsAgreed = useCallback(() => {
setTermsAgreed(!termsAgreed)
}, [ termsAgreed ])
const updateUsername = useCallback(newUsername => {
if (newUsername !== username) {
setUsername(newUsername)
setIsValid(false)
// wait 250ms for user to finish typing before checking
clearTimeout(usernameCheckTimer)
usernameCheckTimer = setTimeout(async () => {
const _valid = isValidUsername(newUsername)
setIsValid(_valid)
if (_valid) {
setCheckingUsername(true)
try {
const ret = await apolloClient.query({
query: GetUsernameAvailabilityQuery,
variables: {
username: newUsername,
},
fetchPolicy: 'network-only',
})
const error = resolveError(ret)
if (error) {
throw error
}
setIsAvailable(_.get(ret, 'data.result.available'))
} catch (err) {
setIsAvailable(false)
}
setCheckingUsername(false)
}
}, 250)
}
}, [ username, apolloClient ])
const completeSignUp = useCallback(async e => {
e.preventDefault()
if (!canSubmit) {
return
}
trackEvent('signup', 'SubmitFinalizeSignUpForm')
const ret = await doRequest({
variables: {
signUp: {
username,
}
}
})
if (_.get(ret, 'data.result.success')) {
trackEvent('signup', 'SubmittedFinalizeSignUpForm')
onComplete(username)
}
}, [ onComplete, username, canSubmit, doRequest ])
let tickContent
if (isValid) {
if (checkingUsername) {
tickContent = <LoadingIcon />
} else {
if (isAvailable) {
tickContent = (
<YesTick>
<Icon name='check-circle' /> Available
</YesTick>
)
} else {
tickContent = (
<NoTick>
<Icon name='times-circle' /> Already taken
</NoTick>
)
}
}
}
return (
<Form className={className} onSubmit={completeSignUp}>
<InstructionsBox>
<p>Your username must be between 3 and 16 characters in length and must
only contain letters (A-Z), numbers (0-9) and hyphens (-).</p>
<p>
<strong>Once set it cannot be changed, so please choose carefully!</strong>
</p>
</InstructionsBox>
<TextInput
size="20"
type="text"
value={username}
onChange={updateUsername}
/>
<TickContainer>
{tickContent}
</TickContainer>
<LegalContainer>
<input type="checkbox" selected={termsAgreed} onClick={toggleTermsAgreed} />
<label>
I have read the <TermsLink>terms and conditions</TermsLink> and <PrivacyLink>privacy policy</PrivacyLink>.
</label>
</LegalContainer>
<Button
type="submit"
disabled={!canSubmit}
loading={_.get(result, 'loading')}
onClick={completeSignUp}
>
Continue
</Button>
<QueryResult {...result} hideLoading={true} />
</Form>
)
}