我想在带有react-apollo的React-Native App上使用GraphQL API。
我的服务器端API正常运行。我在操场上进行的所有测试都完美完成。
另一方面,由于本机反应变得复杂:如何重用服务器端设置的内容? (尤其是突变)我是否必须重复GraphQL代码?
我使用CodeGen(出色的工具!)导出了模式graphql,但是如何在react-native上使用它?
我在React-Native上的配置:
const httpLink = createHttpLink({
uri: API_GRAPHQL_URL,
clientState: {
typeDefs
}
});
const getToken = async () => await AsyncStorage.getItem('userToken');
const authLink = setContext(async (_, { headers }) => {
const token = await getToken();
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
我的typeDefs是在CodeGen上导出的架构,例如:
但是,如何在导出的配置中使用Mutation?我使用react-apollo-hooks
。
尽管我对阿波罗文档有很好的反应,但是GraphQL的客户端部分对我来说还是不太清楚。
有人会帮助我还是有关于该主题的参考文章?
非常感谢您!
答案 0 :(得分:0)
为了重用,您可以创建一个schema.js文件,并将查询从那里导出到相关屏幕,关于Mutations,这里是一个使用Mutation的注册页面示例。
import FormInput from '../components/FormInput';
import FormButton from '../components/FormButton';
import { useMutation } from '@apollo/client';
import { gql } from 'apollo-boost'
const SIGNUP_USER = gql`
mutation SignupMutation($email: String!, $password: String!, $name: String!) {
signupWithEmail(email: $email, password: $password, name: $name) {
user {
email
name
}
}
}`
function SignUp (){
export default function SignUp() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [signupWithEmail] = useMutation(SIGNUP_USER);
const navigation = useNavigation();
const navigation = useNavigation();
return (
<ScrollView>
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<FormInput
style={styles.input}
maxLength={15}
placeholder="name"
onChangeText={name => setName(name)}
value={name}
/>
<FormInput
style={styles.input}
placeholder="email"
onChangeText={email => setEmail(email)}
value={email}
autoCorrect={false}
keyboardType='email-address'
autoCapitalize='none'
/>
<FormInput
style={styles.input}
maxLength={15}
secureTextEntry={true}
placeholder="password"
onChangeText={password => setPassword(password)}
value={password}
/>
<FormButton
title="Signup"
modeValue="contained"
color="#2D374F"
labelStyle={styles.loginButtonLabel}
onPress={() => signupWithEmail({variables: {email, password, name}})}
/>
</View>
</ScrollView>
);
}
您的服务器端解析器应如下所示,请注意我在此处使用firebase。
Mutation: {
signupWithEmail: async (_, { email, password }) => {
const user = firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then((userCredentials) => { return userCredentials.user.updateProfile
({displayName: name})
})
return { user }
},
},
,您的架构应如下所示:
type Mutation {
signupWithEmail(email: String!, password: String!, name: String!): AuthPayload!
loginWithEmail(email: String!, password: String!): AuthPayload!
}
type User {
uid : ID!
email: String!
name: String!
}
type AuthPayload {
user: User!
}