Client leaves channel when sending message in agora Web RTC - reactjs

I am using Agora Web RTC SDK to create a messaging app, but when a client sends a message after successfully logging in and connecting to the channel, it leaves the channel on its own. I have also used event.preventDefault(), still the page reloads and the client leaves the channel.
Following is my code.
import AgoraRTM from 'agora-rtm-sdk';
import { useState } from 'react';
function Chat(){
const [messageContent,setMessageContent]=useState("");
const [channelName,setChannelName]=useState("");
const [channel,setChannel]=useState();
const [token,setToken]=useState();
const [uid,setUid]=useState();
const [userInChannel,setUserInChannel]=useState(false);
const client = AgoraRTM.createInstance("Actual appID", { enableLogUpload: false });
async function handleLogin(event){
await client.login({uid,token})
console.log(client);
setChannel(client.createChannel(channelName));
event.preventDefault();
}
async function handleJoin(){
await channel.join();
setUserInChannel(true);
}
async function handleSend(event){
await channel.sendMessage({text:messageContent})
event.preventDefault();
}
{userInChannel && channel.on('ChannelMessage',({message,memberID})=>{
console.log("channel Message:" ,message);
console.log("member ID:",memberID);
})}
return(
<div>
<form onSubmit={handleJoin}>
<input type='text' name='token' onChange={(event) => { setToken(event.target.value) }} placeholder="Token" />
<input type='text' name='channel' onChange={(event) => { setChannelName(event.target.value) }} placeholder="Channel Name" />
<input type='text' name='uid' onChange={(event) => { setUid(event.target.value) }} placeholder="Enter Uid" />
<div className='button-group'>
<button id='join' type='button' className='btn btn-primary btn-sm' onClick={handleLogin}>Login</button>
<button id='join' type='button' className='btn btn-primary btn-sm' onClick={handleJoin}>Join Channel</button>
</div>
</form>
<form onSubmit={handleSend}>
<input type="text" name="message" value={messageContent} placeholder='Enter your message...' onChange={(event)=>{setMessageContent(event.target.value)}} />
<button>Send</button>
</form>
</div>
)
}
export default Chat;

Related

Clicking on react button asks me to leave site

I am learning react and I have a component which as a 2 input fields and a button, at the moment, clicking on the button will display a message in console log, but when the button is clicked it displays a popup Leave site?, Changes that you made may not be saved.
this is my code in this component
import React, { useRef, useState, Component } from 'react'
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { signOut } from 'firebase/auth';
class InfoLgnTest extends Component {
render() {
this.state = {
user: null
}
return (
<div>
<div className="App">
<SignInWithEmailPassword />
</div>
</div>
)
}
}
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
return (
<>
<div className="form">
<form>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
<input type="submit" onClick={signIn}/>
</div>
</form>
</div>
</>
)
}
export default InfoLgnTest
This code has a form, by default form send data as a request on the same page, for resolve this:
Add onSubmit to form,
call preventDefault method from event
call the function signIn
Change <input type="submit" ... /> to <button type="submit">Send</button>
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
// new function to handle submit
const submitForm = (event) => {
event.preventDefault();
signIn();
}
return (
<>
<div className="form">
{/* Add onSubmit */}
<form onSubmit={submitForm}>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
{/* Change input to button */}
<button type="submit">Send</button>
</div>
</form>
</div>
</>
)
}

Inability to input text in my forms input boxes in react.js

I am unable to type within my label boxes, this has got me incredibly confused as I'm trying to make a simple username/password registration form that logs the data into a database, however this isn't really possible without having the ability to input data. Wondering if I can get some assistance.
import axios from "axios";
import React, { useState } from "react";
export default function Home() {
const [user, setUser] = useState({
username: "",
password: "",
});
const { username, password} = user;
const onInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const onSubmit = async (e) => {
e.preventDefault();
await axios.post("http://localhost:8080/user", user);
};
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3 border rounded p-4 mt-2 shadow">
<h2 className="text-center m-4">Register User</h2>
<form onSubmit={(e) => onSubmit(e)}>
<div className="mb-3">
<label htmlFor="Username" className="form-label">
Username
</label>
<input
type={"text"}
className="form-control"
placeholder="Enter your username"
name="Username"
value={username}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="mb-3">
<label htmlFor="Password" className="form-label">
Password
</label>
<input
type={"text"}
className="form-control"
placeholder="Enter your Password"
name="Password"
value={password}
onChange={(e) => onInputChange(e)}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Submit
</button>
</form>
</div>
</div>
</div>
);
}
I looked at the code but i’m just incredibly confused, it looks fine to me
This is because you don't have the correct names in your input.
Replace Password by password and Username by username.
It has to be the same as in your state.

Sending email in react js

I am new to react. I need to know how to send a mail in react. There is no forms.
When I search in google, everything comes with a form fill up.
I just need a simple function, that triggers to send mail.
Can anyone help with that?
** Used EmailJs https://www.emailjs.com/ here to get the message from the user.**
import emailjs from '#emailjs/browser';
import React, { useRef } from 'react';
function ContactForm() {
const form = useRef();
//console.log('Hello');
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('****', 'template_****', form.current, '****')
.then((result) => {
console.log(result.text);
alert('Message sending successfully!');
form = "";
}, (error) => {
console.log(error.text);
});
};
<div>
<h4>inquiry</h4>
<h3>Stay connected with us</h3>
<form ref={form} onSubmit={sendEmail}>
<div>
<input type="text" id="name" required placeholder='Your full name' name="user_name" />
</div>
<div>
<input type="email" id="email" required placeholder='Your email address' name="user_email" /></div>
<div>
<textarea id="message" required placeholder='Your message' name="message" />
</div>
<button type="submit" value="Send">Send</button>
</form>
</div>
Hope it would be helpful if you only want to get info from user.

ERROR in src\containers\Login.js Line 35:5: Parsing error: Unexpected token (35:5)

Hello guys I'm new in React while watching a tutorial I'm getting this error and I checked it multiple times and compared it with the one in tutorial and can't find any difference. I'm trying to create a user authentication with Django and React. I'm using sublime text 3 as an editor and I have also Visual Studio Code installed. Should I install any extension to handle this problem? Can you help me with this parsing error?
import React, { useState } from 'react';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
const Login = () => {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const { email, password } = formData;
const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = e => {
e.preventDefault();
// login(email, password)
};
// Is the user Authenticated?
// Redirect them to the home page
return (
<div className='container mt-5'>
<h1>
Sign in
</h1>
<p>
Sign into your account
</p>
<form onSubmit={e => onSubmit(e)}>
<div className='form-group'
<input
className='form-control'
type='email'
placeholder='Email'
name='email'
value={email}
onChange={e => onChange(e)}
required
/>
</div>
<div className='form-group'
<input
className='form-control'
type='password'
placeholder='Password'
name='password'
value={password}
onChange={e => onChange(e)}
minLength='6'
required
/>
</div>
<button className='btn btn-primary' type='submit'>Login</button>
</form>
<p className='mt-3'>
Don't have an account? <Link to='/signup'>Sign Up</Link>
</p>
<p className='mt-3'>
Forgot your Password? <Link to='/reset-password'>Reset Password</Link>
</p>
</div)
);
};
// const mapStateToProps = state => ({
// is authenticated?
// });
export default connect(null, { })(Login);
You didn t close the div tag before the input

How to submit file input along with text input to backend in react?

I am trying to submit a file and text input to backend with POST request, the code looks like this,
state={
text:'',
file:''
}
handleTextChange = (e) => {
this.setState({[e.target.name]:e.target.value})
}
handleFileChange = (e) => {
this.setState({file:e.target.files[0]})
}
handleSubmit = (e) => {
const {text,file} = this.state
//POST request with text and file
}
But the file is always empty, If I console.log(e.target.files[0]), it shows a FileList in console but somehow it is not updated in state
I am quite new in react, your help is very much appreciated, thanks
EDIT: the form looks like this
<form action="" className="w-100" onSubmit={(e) => this.handleSubmit(e)}>
<div className="pt-1 pb-3">
<TextAreaAutosize
className="form-control"
placeholder="write some text here"
minRows="4"
name="text"
onChange={(e) => this.handleChange(e)}
/>
</div>
<div className="w-100 d-flex justify-content-between align-items-center">
<div>
<input
type="file"
className="form-control-file"
name="file"
onChange={(e) => this.handleFileChange(e)}
/>
</div>
<div>
<button type="submit" className="btn btn-primary">
Post
</button>
</div>
</div>
</form>
sandbox:
https://codesandbox.io/s/friendly-banzai-8ifw4?fontsize=14&hidenavigation=1&theme=dark
try this one works just fine
before install
run npm install #material-ui/core
import React, { Component } from 'react';
import './App.css';
import { TextareaAutosize } from '#material-ui/core';
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: '',
file: ''
}
this.handleFileChange=this.handleFileChange.bind(this)
this.handleTextChange=this.handleTextChange.bind(this)
this.handleSubmit=this.handleSubmit.bind(this)
}
handleTextChange = (e) => {
this.setState({ [e.target.name]: e.target.value })
}
handleFileChange = (e) => {
console.log(e.target.files[0])
this.setState({ file: e.target.files[0] })
}
handleSubmit = (e) => {
const { text, file } = this.state
}
render() {
return (
<div className="App">
<form action="" className="w-100" onSubmit={(e) => this.handleSubmit(e)}>
<div className="pt-1 pb-3">
<TextareaAutosize
className="form-control"
placeholder="write some text here"
minRows="4"
name="text"
onChange={(e) => this.handleChange(e)}
/>
</div>
<div className="w-100 d-flex justify-content-between align-items-center">
<div>
<input
type="file"
className="form-control-file"
name="file"
onChange={(e) => this.handleFileChange(e)}
/>
</div>
<div>
<button type="submit" className="btn btn-primary">
Post
</button>
</div>
</div>
</form>
</div>
);
}
}
export default App;

Resources