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;
Some State setting you are missing out!