简体   繁体   中英

ReactJS callback useEffect hook

While by following the documentation of GetStreamIO service I am trying to hide the channel message when a user connects to the channel, so that the previous message history will not be shown to a user.

const App = () => {

  const [chatClient, setChatClient] = useState(null);
  const [channel, setChannel] = useState(null);

  useEffect(() => {
    const initChat = async () => {
      const client = StreamChat.getInstance(env.API_KEY);

      const _channel = await client.channel('livestream', env.ROOM_NAME);
      setChatClient(client);
      setChannel(_channel)
    };
    initChat();
  }, []);
  
  useEffect(() => {
    const hideChat = async () => {
      if(channel !== null) {
        console.log(channel);
        await channel.hide();
      }
    }
    hideChat(); 
  }, [channel])

  return (
      <Chat client={chatClient}>
        <Channel channel={channel}>
          <Window>
            <VirtualizedMessageList />
          </Window>
        </Channel>
      </Chat>
  );
};

export default App;

I am going to hide the messages through channel.hide() method after the state value of channel is updated, but this line throws an error of Uncaught (in promise) TypeError: Cannot read property 'hide' of null

在此处输入图像描述

The setChatClient function is async. It is posible that when channel.hide() runs, the channel value is null. I recommend you to hide the channel when it's value has changes:

useEffect(() => {
    if(channel) channel.hide();
}, [channel]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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