'useState in react-native doesn't works on android via EXPO
I'm trying to make an user join a room in socket.io. The event sent from react-native client is :
export default function App() {
const [username, setUsername] = useState('')
const [room, setRoom] = useState('')
const [showChat, setShowChat] = useState(false)
const joinRoom = () => {
if (username === '' || room === '') return
socket.emit('join:room', {room: room, user: username, test: 'test'})
await setShowChat(true)
}
On web browser, it's working fine, and my node.js server receieve
{ room: '2894', user: '5656', test: 'test' }
But on my phone with explo, I correctly connect to web socket, but when I send the 'join:room' event, the server recieve this :
{ test: 'test', user: undefined }
For info, the useState() are updated when user change the TextInput:
<TextInput
style={styles.input}
placeholder='Room...'
onChange={async (event) => {
await setRoom(event.target.value)
}}/>
and the joinRoom() method is called when TouchableOpacity is pressed.
<TouchableOpacity onPress={joinRoom} style={styles.button}>
<Text style={styles.buttonText}> Join a room </Text>
</TouchableOpacity>
Solution 1:[1]
The solution was to talk with hooks like say the documentation:
<TextInput
style={styles.input}
placeholder='Room...'
onChangeText={setRoom}
value={room}
/>
Solution 2:[2]
It seems to me like a strange use of state on your text input.
<TextInput
style={styles.input}
placeholder='Room...'
onChange={async (event) => {
await setRoom(event.target.value)
}}/>
If you're trying to get the state of the text input in your react app through a state variable, I would have expected it to look something like this, in a React Native app:
<TextInput
style = {styles.input}
placeholder = 'Room...'
onChange = {setRoom}
value = {room}
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Neoz |
| Solution 2 |
