react hooks - state lose value in function

1k views Asked by At

I've a problem, I use the react hooks to keep track of the user token and I use the token to identify that user in a socket connection. The problem is that when I mount the component and set the socket the token works as expected, after when the app goes in background I close the socket but when the app come in foreground and I executed the setToken function to re-set the connection the token in the function have his starter value (false). I print the token on screen and also when in the function appear to be false in the screen is printed correctly.

Here my code:


let socket;

const Chat = (props) => {
  const [messages, setMessages] = useState([]);
  const [users, setUsers] = useState({});
  const [token, setToken] = useState(false);

  useEffect(() => {
    init();
    return ()=> { 
      socket.close();
      AppState.removeEventListener('change', appStateChange);  
    }
  }, []);

  const init = async () => {
    // [...] get the token
  };

  const appStateChange = async (newState) => {
    if (newState === "active") {
      setSocket(); //--------- EXECUTING FROM HERE THE TOKEN IS FALSE ---------//
    }
    if (newState !== "active") {
      socket.close();
    }
  }  

  useEffect(() => {
    if (token) {
      setSocket(); //--------- EXECUTING FROM HERE THE TOKEN IS CORRECT ---------//
    }
  }, [token]);

  const setSocket = async () => {
    socket = io("http://192.168.1.172:3000/", {
        query: {
        token: token, 
        userTo: props.userTo
      },
    });

    socket.on("init", (data) => {
      setUsers(data.users);
      setMessages(data.messages);
    });

    socket.on("newMessage", (data) => {
      onReceive({
        _id: data._id,
        text: data.text,
        createdAt: new Date(),
        user: {
          _id: data.user._id,
          name: data.user.name,
          avatar: data.user.avatar,
        },
      });
    });
  };

  const onSend = useCallback((messages = []) => {
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, messages)
    );
    socket.emit("newMessage", messages);
    console.log(messages)
  }, []);

  const onReceive = useCallback((received) => {
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, received)
    );
  }, []);

  return (
    <View style={{flex:1}}>
      <Text>{token}</Text>
      {/*--------- HERE THE TOKEN IS CORRECT ---------*/}
    </View>
  );
};

export default Chat;
1

There are 1 answers

1
Veno On BEST ANSWER

Some State setting you are missing out!

  1. When the app goes to background, you didn't cleared the token.
  2. For appStateChange function parameter newState, from where you are intializing the value
  3. For newState when the app comes to front again, you didn't changed the value so the setSocket() will not be called