[英]Passing input value to my graphql mutation - react/react-apollo
I am using react-apollo
combined with react-native-gifted-chat
. 我正在使用
react-apollo
结合react-native-gifted-chat
。
I am trying to take the input from the user and pass that to my this.props.addMessageToTeam
method. 我试图从用户那里获取输入并将其传递给我的
this.props.addMessageToTeam
方法。
I am having difficulties passing the input value to my graphql
mutation. 我很难将输入值传递给我的
graphql
突变。 Here is what the graphql mutation section looks like: 这是graphql突变部分的样子:
const addMessageToTeam = gql`
mutation {
createMessage(
message: $message,
teamId: "21345667"
) {
id
message
}
}
`;
Please see complete code below: 请在下面查看完整的代码:
import React, { Component } from 'react';
import { View } from 'react-native';
import { GiftedChat, Bubble } from 'react-native-gifted-chat';
import styled from 'styled-components/native';
import gql from 'graphql-tag';
import { graphql, compose } from 'react-apollo';
class Chat extends Component {
state = {
message: '',
messages: [],
}
updateText = (e) => {
this.setState({
message: e
});
}
renderBubble (props) {
return (
<Bubble {...props} />
);
}
sendMessage = (e) => {
this.props.addMessageToTeam(e[0].text);
}
render() {
let allMessages = this.props.data.allMessages || [];
allMessages = allMessages.map(msg => {
return {
_id: msg.id,
text: msg.message,
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://facebook.github.io/react/img/logo_og.png',
}
}
});
return (
<MainContainer>
<GiftedChat
messages={ allMessages }
renderBubble={this.renderBubble}
onInputTextChanged={this.updateText}
onSend={this.sendMessage}
user={{ _id: 12345 }}
/>
</MainContainer>
);
}
}
const MainContainer = styled.View`
display: flex;
flex: 1;
`
const getAllMessages = gql`
query {
allMessages {
id
message
}
}
`;
const addMessageToTeam = gql`
mutation {
createMessage(
message: $message,
teamId: "21345667"
) {
id
message
}
}
`;
export default compose(
graphql(getAllMessages),
graphql(addMessageToTeam, { name: 'addMessageToTeam' }),
)(Chat);
Please let me know if any further information is required. 请让我知道是否需要任何进一步的信息。
In the scenario you presented, the mutation should be called with an object that follows the following structure: 在您介绍的场景中,应使用遵循以下结构的对象来调用突变:
sendMessage = (e) => {
this.props.addMessageToTeam({
variables: {
message: e[0].text,
}
});
}
This is because the graphql mutation was defined with a variable called $message
这是因为graphql突变是使用名为
$message
的变量定义的
You should also change the graphql declaration to: 您还应该将graphql声明更改为:
mutation CreateMessage($message: String) {
createMessage(message: $message, teamId: "21345667")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.