How to close connection when page closed and reloaded? (reactjs) - reactjs

I have a problem with my asp.net core and reactjs app.
I want to fire OnDisconnected method in backend side but I dont know how and when I can call this method?
This is my react code :
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl('https://localhost:5032/hub/notif',
{
accessTokenFactory: () =>Token
})
.withAutomaticReconnect()
.build();
setConnection(newConnection);
console.log(newConnection);
}, []);
useEffect(async () => {
if (connection) {
connection.start()
.then(result => {
console.log('Connected!');
connection.on('RecieveNotification', message => {
console.log(message);
});
})
.catch(e => console.log('Connection failed: ', e));
}
}, [connection]);

Related

React not receive message signalr .net

im trying to implement alerts from backed to my React front with signalr, but actually the client connect successful but not receive alerts(messages) when I send from the backend:
Backend .net 6:
Interface:
namespace BucciaratiMessenger.Hubs
{
public interface IAlertClient
{
Task ReceiveAlert(Alert alert);
}
}
Hub:
namespace BucciaratiMessenger.Hubs
{
public class AlertHub : Hub<IAlertClient>
{}
}
Program:
builder.Services.AddSignalR();
builder.Services.AddCors(options =>
{
options.AddPolicy("ClientPermission", policy =>
{
policy.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:3000")
.AllowCredentials();
});
});
var app = builder.Build();
app.MapHub<AlertHub>("hubs/alert");
Controller:
[Produces("application/json")]
[ApiController]
[Route("api/[controller]")]
public class AlertController :Controller
{
private readonly IHubContext<AlertHub, IAlertClient> _alertHub;
public AlertController(IHubContext<AlertHub, IAlertClient> alertHub)
{
this._alertHub = alertHub;
}
[Route(nameof(AlertController.RegisterAlert)), HttpPost]
public async Task<IActionResult> RegisterAlert(Alert entity)
{
try
{
await _alertHub.Clients.All.ReceiveAlert(entity);
...
}catch(Exception ex)
{
...
}
}
}
React Client:
const HeaderComp = (props) => {
const[connection, setConnection] = useState(null)
const [ alert, setAlert ] = useState([]);
const latestAlert = useRef(null)
const[countAlert, setCountAlert] = useState(0)
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl('http://localhost:5146/hubs/alert')
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
useEffect(() => {
if (connection) {
connection.start()
.then(result => {
console.log('Connected!')
connection.on('ReceiveAlert', message => {
const updatedChat = [...latestAlert.current]
updatedChat.push(message)
setAlert(updatedChat)
setCountAlert(countAlert+1)
});
})
.catch(e => console.log('Connection failed: ', e));
}
}, [connection]);
return (
<Layout>
...
</Layout>
)
}
export default HeaderComp
In the Console.log I get success connection to http://localhost:5146/hubs/alert.
When I send to the method controller any message, not occur any exception, but the client not receive the alert.
The problem were the two useEffect, only need one:
useEffect(() => {
const connection = new HubConnectionBuilder()
.withUrl('http://localhost:5146/hubs/alert')
.withAutomaticReconnect()
.build();
connection.start()
.then(result => {
console.log('Connected!');
connection.on('ReceiveAlert', message => {
setCountAlert(countAlert+1)
});
})
.catch(e => console.log('Connection failed: ', e));
}, []);

SignalR connect setup in react- using useEffects

I'm using "#microsoft/signalr": "^6.0.5", and trying to set up a connection.
It is able to connect with the backend, but I am not sure if my setup looks OK for when the connection fails.
Specifically, I am wondering if the last useEffect is correctly written (the placement of the onClose clause)
useEffect(() => {
const newConnection = new HubConnectionBuilder()
.withUrl(
"https://localhost:3000/workorderHub",
{ accessTokenFactory: () => token, withCredentials: false }
)
.configureLogging(LogLevel.Information)
.withAutomaticReconnect()
.build();
setConnection(newConnection);
}, []);
useEffect(() => {
async function start() {
if (connection) {
try {
connection
.start()
.then(() => {
connection.invoke("SubscribeToProject", projectId); // calling hub method from the client
})
.catch((err) => {
console.error(err.toString());
});
connection.on(
"OperationUpdated",
(projectId, operationId, operation) => {
// function called from the backend Hub
actions.updateSyncedOperation({ operationId, operation });
}
);
} catch (err) {
console.log({ err });
setTimeout(start, 5000);
}
} else {
connection.onclose(async () => {
await start();
});
}
}
start();
}, [connection]);
For React 18 with the new strictMode behaviour i do the following.
It only creates one connection without any errors and it seems to cleanup properly during strictmode behaviour.
export const useLiveUpdates = () => {
const [connectionRef, setConnection] = useState < HubConnection > ();
function createHubConnection() {
const con = new HubConnectionBuilder()
.withUrl(`${EnvService.getUrlHub('url')}`, {
accessTokenFactory: () => AuthService.getToken(),
})
.withAutomaticReconnect()
.build();
setConnection(con);
}
useEffect(() => {
createHubConnection();
}, []);
useEffect(() => {
if (connectionRef) {
try {
connectionRef
.start()
.then(() => {
connectionRef.on('message', () => { ...
});
})
.catch((err) => {
logger.error(`Error: ${err}`);
});
} catch (error) {
logger.error(error as Error);
}
}
return () => {
connectionRef ? .stop();
};
}, [connectionRef]);
};

Socket IO Server is Sending Messages But Client is not Receiving the Message

I am having a weird experience.
I have a Socket IO Server implemented in Spring Boot. When the server sends an event I inspected this in the Chrome Network tab and I discovered that the events are really being sent, but my react js client is not logging the events that were sent. What could be wrong.
Here is my client:
const initSocketIO = () => {
socket.on("connect", (data: any) => {
console.log("I am connected!");
socket.io.emit("test", "Test Data!");
})
socket.on("game", (data: any) => {
console.log("New SocketIO Data Received as: ");
});
socket.on("disconnect", () => {
console.log("I've being disconnected");
});
}
useEffect(() => {
initSocketIO();
return () => {
socket.off("game")
}
}, [loaded]);
Inside the Network Tab in Chrome, I can see that whenever the Server Sends a message, it comes in but the code above is not firing....
Here are the messages as seen under the Network tab on Chrome
How do I fix this?
Thanks.
try putting socket.on inside useEffect.
useEffect(() => {
socket.on("connect", (data: any) => {
console.log("I am connected!");
socket.io.emit("test", "Test Data!");
})
socket.on("game", (data: any) => {
console.log("New SocketIO Data Received as: ");
});
socket.on("disconnect", () => {
console.log("I've being disconnected");
});
return () => {
socket.off("game")
}
}, [loaded]);

Calling axios request one after the other?

I have tow functions in my ReactJs application called,
AuthService.addUser(newUser);
AuthService.userCategories(usercategories);
I want to run these two functions separately, which means the Axios request of the second function should be called after the Axios request of the first function when clicked the submit button. How do I approach the solution? Thanks in advance.
I tried in this way. Is this correct?
const handleSubmit = (e) => {
e.preventDefault();
AuthService.addUser(newUser);
AuthService.userCategories(usercategories);
};
Here are my two functions
addUser: (user) => {
//console.log(post);
axios
.post(CONSTANTS.HOSTNAME + "/api/users/register", user)
.then((res) => {
//save to local storage
const { token } = res.data;
localStorage.setItem("jwtToken", token);
isAuthenticated.next(true);
setAuthToken(token);
Swal.fire({
icon: "success",
title: "Signup Successful!",
showConfirmButton: false,
timer: 1500,
}).then(() => {
window.location.href = "/";
//decode token to get user data
const decoded = jwt_decode(token);
currentUser.next(decoded);
console.log(decoded);
});
})
.catch((err) => {
console.log(err.response.data);
Swal.fire({
icon: "error",
title: "Oops...",
text: err.response.data,
});
// alert(JSON.stringify(err.response.data));
});
},
userCategories: (userCategories) => {
axios
.post(CONSTANTS.HOSTNAME + "/api/users/usercategories", userCategories)
.then((res) => {
console.log(res.data);
});
},
just use promise if function return promise:
const handleSubmit = async (e) => {
e.preventDefault();
await AuthService.addUser();
await AuthService.userCategories();
};
or make promise from function and run async
function one() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('resolve one')
return resolve("i am after five seconds")
},
2000);
});
}
function two() {
return new Promise((resolve, reject) => {
console.log('resolve two')
return resolve("i am after three seconds")
});
}
const handleSubmit = async () => {
console.log('run handleSubmit')
await one();
await two();
}
handleSubmit()

Setup Contentful Javascript SDK in React Native

I'm trying to implement Contentful Javascript SDK on a React Native project (without Expo).
This is the code:
const {createClient} = require('contentful/dist/contentful.browser.min.js')
useEffect(() => {
getContentfulData()
}, [])
const getContentfulData = async () => {
var client = createClient({
adapter: (config) => {
config.adapter = null
return fetch(config)
},
space: '---',
accessToken: '---',
})
await client
.getEntries()
.then((entries) => {
console.log(entries)
})
.catch((error) => {
console.log(error)
})
}
But I'm getting TypeError: Network request failed over and over again.
Any ideas?
const { createClient } = require('contentful/dist/contentful.browser.min.js')
const client = createClient({
space: '*********',
accessToken: '****************************************',
})
client
.getEntries({
content_type: 'trendingBlogs',
})
.then(entry => console.log(entry))
.catch(err => console.log(err))
your missing the getEntries parameters.
i.e
{
content_type: 'trendingBlogs',
}

Resources