I am trying to solve this but I can't, I pass the state from a parent to child component like this:
Main.js
...
const [chatRooms, setChatRooms] = useState([])
const [currentRoom, setCurrentRoom] = useState({})
const prevRoom = useRef()
useEffect(()=>{
const getRooms = async() =>{
const {data} = await axios.get('chat/rooms')
setChatRooms(data)
setCurrentRoom(data[0])
}
getRooms()
},[])
useEffect(()=>{
if (currentRoom !== prevRoom.current)
prevRoom.current = currentRoom
if (prevRoom.current?.id)
disconnect(prevRoom.current.id)
connect()
},[currentRoom])
return (
<ChatSelect rooms={chatRooms} currentRoom={currentRoom.id} setCurrentRoom={setCurrentRoom} />
)
ChatSelect.js
const ChatRoomSelection = ({rooms, currentRoom, setCurrentRoom})=>{
const handleChange = (e) =>{
setCurrentRoom(e.target.value)
//here fails and the selected value can't be set properly in the select option
console.log(currentRoom)
}
return (
<div>
<select name="rooms" value={currentRoom} onChange={(e)=>handleChange(e)}>
{
rooms.map(room=>(
<option value={room.id} key={room.id}>{room.name}</option>
))
}
</select>
</div>
)
}
When I select another chat room, the currentRoom returns the correct id the first time, but when I change it again it returns undefined, what is happening? Thank you.