const [isLoading, setIsLoading] = useState(false);
//this is the whole method where I want to use it
const joinRoom = () => {
const roomKey = roomKeyInput.current.value;
if(roomKey == null)
return
let req = {
sessionId: sessionId,
socketId: socket.id
}
setIsLoading(true)
axios.post(`${hostName}/join-room/${roomKey}`, req)
.then((res)=>{
if(res.data.success){
setIsRoomAdmin(false)
setRoomKey(res.data.roomKey)
setConnectedToRoom(true);
socket.emit('connect-to-room', {
roomKey: roomKey
})
}
}).catch(function (error) {
console.log(error);
});
setIsLoading(false)
}
return (
<>
{isLoading && <Loader />}
</>
)
It works if I manually set the initial value to true, but on updating state it’s not working.
I’m actually using this same logic in other component and this method is working fine there.
I know setting a state is asyncronous but, shouldn’t this work may be with a little delay. I’m using Vite react btw. Sometimes I have to restart server to see the changes but I’ve tried that too.
2
Answers
You start the
.post
, but you aren’t waiting for it to finish. As soon as it has been started, you set loading back to false, and so the loading screen never has a chance to show. You need to wait until you get a success response back (or an error);Because axios’s network requests are asynchronous and pushed to the microtask queue, your
setState
is written in the synchronous task code, so thesetState
is executed twice at once, so you need to wait for the network request to complete before you executesetState