我想使用一个反应上反应本机应用程序与反应阿波罗的GraphQL应用程序接口。
我的服务器端API是有效的。我在操场上的所有测试都运行得很好。
另一方面,由于反应原生的事情变得复杂:如何重用服务器端设置的内容?(特别是突变)我必须复制GraphQL代码吗?
我使用CodeGen (很棒的工具!)导出了我的schema 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上导出的模式,例如:

但是,如何在我导出的配置中使用突变?我使用react-apollo-hooks。
GraphQL的客户端部分对我来说不是很清楚,尽管有很大的反应-阿波罗文档。
有没有人能帮助我,或者有一篇关于这个主题的参考文章?
非常感谢!
发布于 2020-06-16 03:55:28
为了重用,您可以创建一个schema.js文件,并将您的查询从那里导出到相关屏幕,关于突变,这里是一个使用突变的signUp页面示例。
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!
}
https://stackoverflow.com/questions/57028431
复制相似问题