Skip to content

Instantly share code, notes, and snippets.

@maiquealmeida
Created August 23, 2019 21:57
Show Gist options
  • Save maiquealmeida/58ac5f9d73d540196cbd73b42b9b7fb6 to your computer and use it in GitHub Desktop.
Save maiquealmeida/58ac5f9d73d540196cbd73b42b9b7fb6 to your computer and use it in GitHub Desktop.
Minhas melhores configurações do Apollo Client no React Native
import React from 'react';
import { Alert } from 'react-native';
import {ApolloClient} from 'apollo-client';
import {InMemoryCache} from 'apollo-cache-inmemory';
import {HttpLink} from 'apollo-link-http';
import {onError} from 'apollo-link-error';
import {withClientState} from 'apollo-link-state';
import {ApolloLink, Observable} from 'apollo-link';
import AsyncStorage from '@react-native-community/async-storage';
const cache = new InMemoryCache({
cacheRedirects: {
Query: {
movie: (_, {id}, {getCacheKey}) => getCacheKey({__typename: 'Movie', id}),
},
},
});
const request = async operation => {
const token = await AsyncStorage.getItem('token');
operation.setContext({
headers: {
authorization: token,
},
});
};
const requestLink = new ApolloLink(
(operation, forward) =>
new Observable(observer => {
let handle;
Promise.resolve(operation)
.then(oper => request(oper))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return () => {
if (handle) {
handle.unsubscribe();
}
};
})
);
const client = new ApolloClient({
link: ApolloLink.from([
onError(({graphQLErrors, networkError}) => {
if (graphQLErrors) {
graphQLErrors.forEach(({message, locations, path}) => {
console.tron.log(
`[GraphQL error] ==> Message: ${message}, Location: ${locations}, Path: ${path}`
);
Alert.alert('Erro na consulta a API', message);
}
);
}
if (networkError) {
console.tron.log(`[Network error] ==> message: ${networkError}`);
Alert.alert('Erro na conexão com a rede', `${networkError}`);
}
}),
requestLink,
withClientState({
defaults: {
isConnected: true,
},
resolvers: {
Mutation: {
updateNetworkStatus: (_, {isConnected}, {cache}) => {
cache.writeData({data: {isConnected}});
return null;
},
},
},
cache,
}),
new HttpLink({
uri: 'http://localhost:4000/',
credentials: 'include',
}),
]),
cache,
});
export default client;
import React from 'react';
import Routes from '~/routes';
import {ApolloProvider} from '@apollo/react-hooks';
import client from '~/services/apollo';
const App = () => {
return (
<ApolloProvider client={client}>
<PaperProvider theme={theme}>
<Routes />
</PaperProvider>
</ApolloProvider>
);
};
import React, {useState} from 'react';
import gql from 'graphql-tag';
import {useMutation} from '@apollo/react-hooks';
const LOGIN_MUTATION = gql`
mutation Login($username: String!, $password: String!) {
login(username: $username, password: $password) {
user {
ID
NOME
CPF
MATRICULA_TERCEIRO
CHAPA_RM
}
token
}
}
`;
export default function Login() {
const [checked, setChecked] = useState('unchecked');
const [username, setUsername] = useState('maique.almeida');
const [password, setPassword] = useState('1234567');
const [login, {data, loading, error}] = useMutation(LOGIN_MUTATION);
const handleLogin = async () => {
console.tron.log(`Efetuando login com ${username}`);
await login({variables: { username, password } });
console.tron.log(data, loading, error);
};
return (
<Container>
<TextInput
ref={txtUsername}
mode="outlined"
style={styles.input}
label="Usuario"
value={username}
onChangeText={text => setUsername(text)}
/>
<TextInput
ref={txtPassword}
mode="outlined"
style={styles.input}
label="Senha"
value={password}
onChangeText={text => setPassword(text)}
/>
<Button
icon="check"
mode="contained"
dark={true}
color={'#339966'}
onPress={handleLogin}>
ENTRAR
</Button>
</Container>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment