WebRTC stream doesn't appear (simple-peer) - webrtc

I am trying to make a video call using simple-peer and I tried a lot with same code but sometimes I can see what I expected but it doesn't always work well. At first, I tried to manage 'userStream' by useState but setState is asynchronous so I couldn't get the stream. I tweaked that as 'let userStream = null'. I guess this way is not stable as well so it doesn't work sometimes.
I don't know what is the problem...
const myVideo = useRef();
const userVideo = useRef();
const connectionRef = useRef();
const roomName = '123';
let userStream = null;
let creator = false;
useEffect(() => {
const socket = io('https://jg-jg.shop');
socket.emit('joinRoom', roomName);
socket.on('created', () => {
creator = true;
navigator.mediaDevices
.getUserMedia({ video: true, audio: true })
.then((stream) => {
userStream = stream;
myVideo.current.srcObject = stream;
console.log(1);
});
});
socket.on('joined', () => {
navigator.mediaDevices
.getUserMedia({ video: true, audio: true })
.then((stream) => {
userStream = stream;
myVideo.current.srcObject = stream;
console.log(2);
});
socket.emit('ready', roomName);
});
socket.on('ready', () => {
if (creator) {
const peer = new Peer({
initiator: true,
trickle: false,
stream: userStream,
});
peer.on('signal', (signal) => {
socket.emit('sendingSignal', { signal, roomName });
console.log(3);
});
peer.on('stream', (stream) => {
userVideo.current.srcObject = stream;
console.log(4);
});
socket.on('receivingSignal', (signal) => {
peer.signal(signal);
console.log(5);
});
connectionRef.current = peer;
}
});
socket.on('offer', (incomingSignal) => {
if (!creator) {
const peer = new Peer({
initiator: false,
trickle: false,
stream: userStream,
});
peer.on('signal', (signal) => {
socket.emit('returningSignal', { signal, roomName });
console.log(6);
});
peer.on('stream', (stream) => {
userVideo.current.srcObject = stream;
console.log(7);
});
peer.signal(incomingSignal);
console.log(8);
connectionRef.current = peer;
}
});
}, []);

Related

Could not decode base64 when uploading image (file size 1mb or more)

ReacJs This is the react js code that i used the get the avatar image and send it to backed
const handleSignup = async (event) => {
event.preventDefault();
const formdata = new FormData();
formdata.set("name", signupstate.name);
formdata.set("email", signupstate.email);
formdata.set("password", signupstate.password);
formdata.set("confirmpassword", signupstate.confirmpassword);
formdata.set("avatar", avatar);
const isValid = createSignupValidation(signupstate, avatar, alert);
if (isValid) {
const res = await createSignUpApi(formdata, alert); // api call
if (res.status === 201) {
alert.success("User Registered Successfully");
navigate("/");
}
}
};
const handleSingnupInput = (event) => {
if (event.target.name === "avatar") {
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = () => {
if (reader.readyState === 2) {
setAvatarPreview(reader.result);
setAvatar(reader.result);
}
};
} else {
setSignUpState({
...signupstate,
[event.target.name]: event.target.value,
});
}
};
NodeJs Here the image is uploaded to cloudinary
const cloudinary = require("cloudinary");
exports.signupController = catchAsyncErrors(async (req, res, next) => {
const { name, email, password, confirmpassword } = req.body;
const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar, { folder: "ecommerce_users", width: 150, crop: "scale", });
const user = await User.create({ name, email, password, confirmpassword, avatar: { public_id: myCloud.public_id, url: myCloud.secure_url, }, });
sendTokenToCookie(user, 201, res);
});
{ "success": false, "message": "Could not decode base64"

UseState variable not updating after setting it within a function - React Native

Howcome when i setURL(value) or setURL(val) it doesnt actually set the state?
Only when I press the upload button a second time it sets the state correctly..
First time run:
My initialized state:
const [URL, setURL] = useState();
The function to get the downloadURL:
await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
var value = val;
setURL(value)
}).catch((error)=>{
Alert.alert(error.message);
});
Upload button function:
My code:
const AddPost = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const [Color, setColor] = useState('')
const [Desc, setDesc]= useState('');
const [location, setlocation] = useState('');
const navigation = useNavigation()
const [image, setImage] = useState(null);
const [URI, setURI] = useState(Result);
const [Result, setResult] = useState();
const [URL, setURL] = useState();
const [uploading, setUploading] = useState(false);
const usersCollectionRef = collection(db, "Posts");
const createPost = async () =>
{
setUploading(true);
let url = await uploadImageAsync(URI);
console.log("from upload btn: "+URL)
await addDoc(usersCollectionRef, { username: auth.currentUser?.email, Colour: Color, Injured: value2, Type: value3, Collar: isEnabled ? 'Yes' : 'No', Welfare: value4, status: value, Description: Desc, picture: URL, location: location })
Alert.alert("Successfully uploaded!");
navigation.navigate('MainScreen');
setUploading(false);
};
const TakeImage = async () => {
let result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
quality: 0.6,
});
if (!result.cancelled) {
setImage(result.uri);
setURI(result.uri);
}
};
const BrowseImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
quality: 0.6,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
setURI(result.uri);
}
};
const uploadImageAsync =async(uri)=> {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
const fileRef = ref(getStorage(), uuid.v4());
const result = await uploadBytes(fileRef, blob);
let url = await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
setURL(val);
return val;
}).catch((error)=>{
Alert.alert(error.message);
});
return url;
}
Since updating state is an asynchronous method so the state will not get updated immediately. You'll have to work around like this -
const uploadImageAsync =async(uri)=> {
// rest of your code
let url = await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
setURL(val);
return val;
}).catch((error)=>{
Alert.alert(error.message);
});
return url;
}
And then in your onPress function:-
const createPost = async () => {
let url = await uploadImageAsync(URI);
// Rest of your code
}

Hash value null error in react-native hooks useEffect

the hash data I received using asyncStorage in my react native project is wrong. It actually works when I refresh the page. My request is probably running earlier than hash. However, I could not find a solution to this.
const [info, setInfo] = useState('');
const [hash, setHash] = useState(null);
const _retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('hash');
setHash(value)
} catch (error) {
// Error retrieving data
}
};
useEffect(() => {
_retrieveData()
setTimeout(() => {
console.log(hash) //
axios.get(apiUrl + 'loginInfo?hash=' + hash)
.then(response => {
setInfo(response.data.message);
console.log('res', response);
});
}, 1000);
}, []);
The _retriveData method should be inside of the useEffect.
const [info, setInfo] = useState('');
const [hash, setHash] = useState(null);
useEffect(() => {
const _retrieveData = async () => {
try {
const hash = await AsyncStorage.getItem('hash');
return hash
} catch (error) {
console.log('error',error);
// Error retrieving data
}
};
const hash = _retrieveData()
setTimeout(() => {
console.log(hash) //
axios.get(apiUrl + 'loginInfo?hash=' + hash)
.then(response => {
setInfo(response.data.message);
console.log('res', response);
});
}, 1000);
}, []);
I solved the problem by getting help from a friend.
const [info, setInfo] = useState({});
const [hash, setHash] = useState(null);
const _retrieveData = useCallback(async () => {
try {
const value = await AsyncStorage.getItem('hash');
setHash(value);
} catch (error) {
// Error retrieving data
}
}, []);
const getInfo = useCallback(async () => {
try {
const response = await axios.get(apiUrl + 'loginInfo?hash=' + hash);
setInfo(response.data.message)
} catch (e) {
console.log(e);
}
}, [hash]);
useEffect(() => {
if (!hash) {
_retrieveData();
}
}, [hash])
useEffect(() => {
if (hash) {
setTimeout(() => {
getInfo();
},500)
}
}, [hash, getInfo]);

can not read/write data in function

Hi i am use vue and axios for upload file
Does not recognize the list inside in onUploadProgress
code
data: ()=>({
list: [
{ id:0, icon: 'image', iconClass: 'blue white--text', title: 'Vacation itinerary', file:"asasf.png", progress:100 },
selectedFile: null
]
}),
methods:{
async startUpload(){
let formData = await new FormData();
await formData.append('file', this.selectedFile);
this.selectedFile=null
let config = {
onUploadProgress: function(progressEvent){
console.log(this.list) //is null
this.list[id].progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
}
};
this.$axios.$post('/upload/insert', formData, config)
.then(response => {
this.list[id].progress=100
this.list[id].file=response.data.path
})
.catch(error => {
console.log(error)
})
}
}
console.log(this.list) in lone 16 is null
Just change onUploadProgress function to arrow function, otherwise this will be related to the context of onUploadProgress instead of the component.
async startUpload(){
let formData = await new FormData();
await formData.append('file', this.selectedFile);
this.selectedFile=null
let config = {
onUploadProgress: (progressEvent) => {
console.log(this.list) //is null
this.list[id].progress = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
}
};
this.$axios.$post('/upload/insert', formData, config)
.then(response => {
this.list[id].progress=100
this.list[id].file=response.data.path
})
.catch(error => {
console.log(error)
})
}

How to save picture to API in react native with Expo?

I am building a react native apps and there's a feature to change user's profile picture. And I use camera from expo to take a new profile picture, since I built my react native apps using crna.
I tried the tutorial in this following snippet.
_takePhoto = async () => {
const {
status: cameraPerm
} = await Permissions.askAsync(Permissions.CAMERA);
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (cameraPerm === 'granted' && cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
}
};
_pickImage = async () => {
const {
status: cameraRollPerm
} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (cameraRollPerm === 'granted') {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
}
};
_handleImagePicked = async pickerResult => {
let uploadResponse, uploadResult;
try {
this.setState({
uploading: true,
});
if (!pickerResult.cancelled) {
uploadResponse = await uploadImageAsync(pickerResult.uri);
uploadResult = await uploadResponse.json();
this.setState({
picture_profile: uploadResult.location
});
}
}
catch (e) {
console.log({ uploadResponse });
console.log({ uploadResult });
console.log({ e });
Alert.alert('Upload failed, sorry :(');
} finally {
this.setState({
uploading: false,
});
}
};
async function uploadImageAsync(uri){
let apiUrl= `someURL`;
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append('photo', {
uri,
name:`photo.${fileType}`,
type: `picture_profile/${fileType}`,
});
//update_password
let option ={
method: 'POST',
body: formData,
headers: {
Authorization: token,
'content-type': 'multipart/form-data',
},
};
return fetch(apiUrl, option);
}
But I failed to save the picture to API. Also I got this error message when I try to upload a picture.
Possible Unhandled Promise Rejection (id:2): TypeError this._handleImagePicked is not a function
Can anyone please help me what to do? Thank you in advance.