Search code examples
javascriptreactjsgraphqluse-effect

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. 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. However, on the console I can clearly see the messages that I want to print. What is the problem of the function in UseEffect()? I would be so appreciated if anyone can help .


Solution

  • {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.

    Replace with this

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