简体   繁体   中英

try to call a function object which uses a state variable that is changed inside useEffect, and get undefined state variable

Since my currentUser state variable is set in useEffect, and getJoinRoom requires currentUser so I set useCallback on getJoinRoom with dependency currentUser state, but it seems that currentUser is still not set when calling getJoinRoom

Error on connection TypeError: Cannot read property 'getJoinableRooms' of undefined

function App() {
  const [messages, setMessages] = useState([]);
  const [currentUser, setCurrentUser] = useState();
  const [joinableRooms, setJoinableRooms] = useState([]);
  const [joinedRooms, setJoinedRooms] = useState([]);

  const sendSimpleMessage = (text) => {
    // send simple text
    currentUser.sendSimpleMessage({
      text: text,
      roomId: '7b7a1d23-e869-4c19-8eab-e88d5144dd72'
    });
  }

  const subscribeToRoom = (roomId) => {
    setMessages([]);
    currentUser.subscribeToRoomMultipart({
      // roomId: '7b7a1d23-e869-4c19-8eab-e88d5144dd72',
      roomId: roomId,
      hooks: {
        onMessage: message => {
          // console.log('message object: ', message.parts[0].payload.content);
          setMessages(prevMessages => [...prevMessages, message]);
        }
      }
    })
  };

  const getJoinRoom = useCallback(() => {
    currentUser.getJoinableRooms()
      .then(joinableRooms => {
        setJoinableRooms(joinableRooms);
        setJoinedRooms(currentUser.rooms);
      }).catch(err => {
        console.log('Error on getting joinable rooms', err);
      });
  }, [currentUser])

  useEffect(() => {
    const chatManager = new ChatManager({
      instanceLocator: instanceLocator,
      userId: 'Henry',
      tokenProvider: new TokenProvider({
        url: tokenUrl
      })
    });

    chatManager.connect()
      .then(currUser => {
        setCurrentUser(currUser);

        //currUser.getJoinableRooms()
        //  .then(joinableRooms => {
        //    setJoinableRooms(joinableRooms);
        //    setJoinedRooms(currUser.rooms);
        //  }).catch(err => {
        //    console.log('Error on getting joinable rooms', err);
        //  });

        getJoinRoom();

      }).catch(err => {
        console.log('Error on connection', err)
      })

  }, [getJoinRoom]);

  return (
    <div className="app">
      <RoomList
        rooms={[...joinableRooms, ...joinedRooms]}
        subscribeToRoom={subscribeToRoom}
      />
      <MessageList messages={messages} />
      <SendMessageForm sendSimpleMessage={sendSimpleMessage} />
      <NewRoomForm />
    </div>
  );
}

export default App;

Not a react dev.

You cannot access a let/const declared variable in TDZ . Use function declaration instead.

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