[Ошибка GraphQL]: Сообщение: Невозможно преобразовать свойство id в значение undefined или null. Местоположение: [объект объекта], Путь: newMessage
Я новичок в хуках React/Apollo и пытаюсь попрактиковаться в этой концепции, чтобы лучше ее понять.
Поэтому я попробовал протестировать его с помощью React-Native-Gifted-Chat и Apollo Client.
Запрос и Мутация работают очень хорошо, за исключением подписки.
У меня проблемы с обработчиком useSubscription, он зависает в состоянии загрузки. Поэтому я попробовал другой метод, используя метод subscribeToMore в хуке useQuery.
Теперь вот проблема, я хотел обновлять данные всякий раз, когда кто-то отправляет сообщение в комнату чата, и это ошибка, которую я получал до сих пор.
[Ошибка GraphQL]: сообщение: не удается разрушить свойство
id
of 'undefined' или 'null'., Location: [object Object], Path: newMessage - node_modules/expo/build/environment/muteWarnings.fx.js:18:23 in warn - ... еще 17 кадров стека из фреймворка внутренности
Вот код моего проекта React Native
App.js
import React, { Suspense } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NativeRouter, Route, Link } from "react-router-native";
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';
import Home from './screens/ChatScreen';
const client = new ApolloClient({
uri: 'http://192.168.1.110:4000',
});
export default function App() {
return (
<ApolloProvider client={client}>
<NativeRouter>
<Route exact path="/" component={Home} />
</NativeRouter>
</ApolloProvider>
)
}
ChatScreen.js
import React, { useState, useEffect, useCallback } from 'react';
import { StyleSheet, Text, View, Platform, KeyboardAvoidingView } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat'
import { gql } from "apollo-boost";
import { useQuery, useMutation, useSubscription } from '@apollo/react-hooks';
const GET_MESSAGES = gql`
query Messages($roomId: String!){
getMessages(roomId: $roomId) {
id
user_id
room_id
parts {
content
type
}
created_at
updated_at
}
}
`;
const SUBSCRIBE_MESSAGES = gql`
subscription SubMessage($roomId: String!) {
newMessage(roomId: $roomId) {
id
user_id
room_id
parts {
content
type
}
created_at
updated_at
}
}
`;
const SEND_MESSAGE = gql`
mutation SendMessage($roomId: String!, $text: String!) {
sendMessage(room_id:$roomId, text: $text)
}
`;
export default function ChatScreen() {
const [messages, setMessages] = useState([]);
const { loading, data, subscribeToMore } = useQuery(GET_MESSAGES, {
variables: {
roomId: "47dfe0eb-2bfb-43ac-bbdb-1c684d16d78a"
}
});
const [addMessage, { data: mutationData }] = useMutation(SEND_MESSAGE);
useEffect(() => {
let messageList = [];
if (data && data.getMessages) {
data.getMessages.map(message => {
messageList.push({
_id: message.id,
text: message.parts[0].content,
createdAt: message.created_at,
user: {
_id: message.user_id,
name: message.user_id,
avatar: 'https://placeimg.com/140/140/any',
},
})
})
}
setMessages([
...messageList
]);
subscribeToMore({
document: SUBSCRIBE_MESSAGES,
variables: {
roomId: "47dfe0eb-2bfb-43ac-bbdb-1c684d16d78a"
},
updateQuery: (previousResult, { subscriptionData }) => {
console.log(subscriptionData)
}
});
}, [data]);
onSend = (msgs = []) => {
addMessage({
variables: {
roomId: "47dfe0eb-2bfb-43ac-bbdb-1c684d16d78a",
text: msgs[0].text
}
});
setMessages(GiftedChat.append(messages, msgs))
}
if (loading) {
return (
<View style={styles.container, { justifyContent: 'center', alignItems: 'center'}}>
<Text>Loading....</Text>
</View>
)
}
return (
<View style={styles.container}>
<GiftedChat
messages={messages}
onSend={msg => onSend(msg)}
user={{
_id: 'test',
}}
/>
{
Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />
}
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});