简体   繁体   English

使用 React UseEffect() 从 GraphQL 获取数据

[英]Using React UseEffect() to fetch data from GraphQL

I'm trying to fetch data from graphQL, and I know that by putting function into the react UseEffect() , I would be able to call the function once the data is updated and constructed.我正在尝试从 graphQL 中获取数据,并且我知道通过将 function 放入 react UseEffect()中,我将能够调用 ZC1C425268E68385D1AB5074C17A94 并更新数据。 However, I'm working on a chatroom, and the data does not appear on the screen:但是,我正在使用聊天室,并且数据没有出现在屏幕上:

import {
  CREATE_MESSAGE_MUTATION,
  MESSAGES_QUERY,
  MESSAGE_SUBSCRIPTION,
} from "../graphql";
import { useQuery, useSubscription } from "@apollo/client";
import React, { useEffect } from "react";
import { Tag } from "antd";
const ChatBox = ({ me, friend, ...props }) => {
  //me friend are strings

  const chatBoxName = [me, friend].sort().join("_");
  const { loading, error, data, subscribeToMore } = useQuery(MESSAGES_QUERY, {
    variables: { name: chatBoxName },
  });

  useEffect(() => {
    try {
      subscribeToMore({
        document: MESSAGE_SUBSCRIPTION,
        variables: { name: chatBoxName },
        updateQuery: (prev, { subscriptionData }) => {
          if (!subscriptionData.data) return prev;
          const newMessage = subscriptionData.data;
          console.log("Subscribing more data: ", newMessage);
        },
      });
    } catch (e) {
      console.log("Error in subscription:", e);
    }
  }, [subscribeToMore]);

  if (loading) return <p>loading ...</p>;
  if (error) return <p>Error in frontend chatbox: {error}</p>;

  return (
    <div className="App-messages">
      {console.log(data.chatboxs[0].messages)}
      {data.chatboxs[0].messages.map(({ sender: { name }, body }) => {
        <p className="App-message">
          <Tag color="blue">{name}</Tag>
          {body}
        </p>;
      })}
    </div>
  );
};

export default ChatBox;

After a small delay of loading... , it turns to the <div className="App-messages"> with no messages inside.loading...的一小段延迟后,它转到<div className="App-messages">里面没有消息。 However, on the console I can clearly see the messages that I want to print.但是,在控制台上,我可以清楚地看到要打印的消息。 What is the problem of the function in UseEffect() ? UseEffect()中的 function 有什么问题? I would be so appreciated if anyone can help.如果有人可以提供帮助,我将不胜感激。

{data.chatboxs[0].messages.map(({ sender: { name }, body }) => { // <- this part
    <p className="App-message">
      <Tag color="blue">{name}</Tag>
      {body}
    </p>;
  })}

As a callback, you declared a function that does not return JSX elements.作为回调,您声明了一个不返回 JSX 元素的 function。

Replace with this换成这个

{data.chatboxs[0].messages.map(({ sender: { name }, body }) => (
    <p className="App-message">
      <Tag color="blue">{name}</Tag>
      {body}
    </p>;
  ))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM