const Video = require("");
const token = "";
const connectOptions = {logLevel: "off"}
const startRoom = function(token) {
console.log("hello world");
Video.connect(a)
.then(room => null
})
.catch(error => {
console.log("error");
return error
});
}
The async/await will lead to removal of catch. Which is what I want to achieve.
Just fyi, you're not using await INSTEAD of promises, you're using await WITH promises. async functions return promises, and await waits for promises to resolve
const Video = require("twilio-video");
const token = "test_token";
const connectOptions = {video: false, audio: false, logLevel: "off"}
const startRoom = async function(token) {
console.log("hello world");
try {
const room = await Video.connect(token, connectOptions)
console.log("got a room");
} catch(error) {
console.log("error");
}
}
Just wrap it in try-catch
const getRoom = async () => {
try {
const room = await Video.connect(token, connectOptions);
console.log("got a room");
} catch (e) {
console.log("error");
}
}
or you can use this also..
async function startRoom(token) {
console.log("hello world");
try {
let response = await fetch(token);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
let room = await video.connect(token, connectOptions);
console.log("got a room");
}
} catch (e) {
console.log(e);
}
}
Related
I am working on a react app and I use tokens and refresh tokens for authentication. Whenever the backend returns a 401, the axios.interceptors.response picks it up and tries to refresh my token. If it succeeds, it will reinitiate the original call with the updated headers. See the code below:
// To avoid infinite loops on 401 responses
let refresh = false;
axios.interceptors.response.use(
(resp) => resp,
async (error) => {
if (error.response.status === 401 && !refresh) {
refresh = true;
const response = await axios.post(
"/api/auth/refresh",
{},
{ withCredentials: true }
);
if (response.status === 200) {
axios.defaults.headers.common[
"Authorization"
] = `Bearer ${response.data["accessToken"]}`;
return axios(error.config);
}
}
refresh = false;
return error.response;
}
);
This by itself works great, but not in combination with the code below in one of my components:
const [pages, setPages] = useState();
const [error, setError] = useState();
const navigate = useNavigate();
useEffect(() => {
async function fetchInfo() {
const response = await getMyPages();
if (response.status === 200) {
setPages(response.data);
}
else if (response.status === 401) {
setError(t("error.notAuthorized"));
navigate(`/login`, { replace: true });
}
// Any other error
else {
setError(t("error.unexpected"));
}
}
fetchInfo();
}, [t, navigate]);
// getMyPages function
export async function getMyPages() {
try {
const result = await axios.get(`/api/user/mypages`);
return result;
} catch (err) {
return err.response;
}
}
The problem is that the user is navigated to /login before the new request (with refreshed token) is made and finished. So when the new request finishes, I am not in the original component anymore and I can no longer update the pages state.
Any suggestions on how to handle this?
useEffect(() => {
let isMounted = true;
const controller = new AbortController();
const getMyPages = async () => {
try {
const response = await axios.get(`/api/user/mypages`, {
signal: controller.signal
});
isMounted && setPages(response.data);
} catch (err) {
navigate(`/login`, { replace: true });
}
}
getMyPages();
return () => {
isMounted = false;
controller.abort();
}
}, [])
My .net core react web application works fine, except that when I try to publish it gives me the following error:
Occurred while linting C:\.....Fetch.js: 79
Rule: "react-hooks/exhaustive-deps"
This is my code:
const populateTable1Data = async () => {
var response = await axios.get(apiurl + { params: { id: props.id1 } });
var data = await response.data;
setTable1Data(data);
}
const populateTable2Data = async () => {
var response = await axios.get(apiurl + { params: { id: props.id2 } });
var data = await response.data;
setTable2Data(data);
setLoading(false);
}
useEffect(() => {
const load = async () => {
await populateTable1Data();
await populateTable2Data();
setLoading(false)
}
load()
}, []);
Problem is that I have a very similar useEffect inside another component which doesn't give errors though:
const populateTableData = async () => {
const response = await axios.get(apiurl + key);
const data = await response.data;
setTableData(data);
setLoading(false);
}
useEffect(() => {
populateTableData();
}, [])
If anyone has the same problem, I solved by doing this:
const populateTable1Data = async (dataProps) => {
var response = await axios.get(apiurl + { params: { id: dataProps.id1 } });
var data = await response.data;
setTable1Data(data);
}
const populateTable2Data = async (dataProps) => {
var response = await axios.get(apiurl + { params: { id: dataProps.id2 } });
var data = await response.data;
setTable2Data(data);
setLoading(false);
}
useEffect(() => {
const load = async () => {
await populateTable1Data(props);
await populateTable2Data(props);
setLoading(false)
}
load()
}, [props]);
I essentially passed the props on the function call, I don't know why does it have to be this way, I'll leave the answer here in case anyone else needs it while waiting for someone to be kind enought to explain the reason for this.
nestjs controller.ts
#Patch(':id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
#Body('shippingAddr') addrShipping: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling, addrShipping);
return null;
}
nestjs service.ts
async updateProduct(
addressId: string,
addrBilling: boolean,
addrShipping: boolean,
) {
const updatedProduct = await this.findAddress(addressId);
if (addrBilling) {
updatedProduct.billingAddr = addrBilling;
}
if (addrShipping) {
updatedProduct.shippingAddr = addrShipping;
}
updatedProduct.save();
}
there is no problem here. I can patch in localhost:8000/address/addressid in postman and change billingAddr to true or false.the backend is working properly.
how can i call react with axios?
page.js
const ChangeBillingAddress = async (param,param2) => {
try {
await authService.setBilling(param,param2).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
return....
<Button size='sm' variant={data.billingAddr === true ? ("outline-secondary") : ("info")} onClick={() => ChangeBillingAddress (data._id,data.billingAddr)}>
auth.service.js
const setBilling = async (param,param2) => {
let adressid = `${param}`;
const url = `http://localhost:8001/address/`+ adressid ;
return axios.patch(url,param, param2).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
I have to make sure the parameters are the billlingddress field and change it to true.
I can't make any changes when react button click
Since patch method is working fine in postman, and server is also working fine, here's a tip for frontend debugging
Hard code url id and replace param with hard coded values too:
const setBilling = async (param,param2) => {
// let adressid = `${param}`;
const url = `http://localhost:8001/address/123`; // hard code a addressid
return axios.patch(url,param, param2).then((response) => { // hard code params too
console.log(response); // see console result
if (response.data.token) {
// localStorage.setItem("user", JSON.stringify(response.data));
}
// return response.data;
})
}
now it worked correctly
#Patch('/:id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling);
return null;
}
const ChangeBillingAddress = async (param) => {
try {
await authService.setBilling(param,true).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
const setBilling= async (param,param2) => {
let id = `${param}`;
const url = `http://localhost:8001/address/`+ id;
return axios.patch(url,{billingAddr: param2}).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
Here's how I tried to do it, but it didn't work
useEffect(() => {
try {
const response = async() => {
await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
console.log(response.data)
} catch (e) {
console.log(e);
}
})
And so it should look in class components
async componentDidMount() {
try {
const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
console.log(response.data)
} catch (e) {
console.log(e);
}
}
You are defining your response as a function (that is never used) rather to do a request call .
Try to split you request function and the useEffect like this (maybe the useEffect don't permit async functions as its parameter).
Maybe this is the correct way to do what you want.
async function request(){
const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')
console.log(response.data)
}
useEffect(async () => {
try {
request()
} catch (e) {
console.log(e);
}
})
I believe you forgat to use the response to convert it to a useable data
useEffect(() => {
try {
const response = async() => {
await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
const dataUser = await response.json(); //THIS LINE
console.log(dataUser)
} catch (e) {
console.log(e);
}
})
And so it should look in class components
async componentDidMount() {
try {
const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
const dataUser = await response.json(); //THIS LINE
console.log(dataUser)
} catch (e) {
console.log(e);
}
}
I got a few examples in this Github repository
you must define a function and call it after
useEffect(() => {
const fetchData=async()=>{
try {
const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')
console.log(response.data)
} catch (e) {
console.log(e);
}
};
fetchData();
})
I am trying to upload an image to firebase storage however I am getting the error object Object as shown below
Please may someone help me I have never uploaded an image to firebase and really need assistance . Any help what's so ever will be much appreciated. Thank you sooo much in advance!!!!!
This is my code. I've Initialized firebase as well as my image path postImage works as expected.
const handleSubmit = () => {
if (postImage !== undefined) {
const fileExtention = postImage[0].split('.').pop()
console.log(`EXT ${fileExtention}`)
const fileName = `${uniqid}.${fileExtention} `
const reference = firebase.storage().ref(`Posts/images/${fileName}`)
reference.put(postImage)
.on(
firebase.storage.TaskEvent.STATE_CHANGED,
snapshot => {
console.log(`snapshot ${snapshot.state}`)
console.log(`progress ${(snapshot.bytesTransferred / snapshot.totalBytes) * 100}`)
if (snapshot.state === firebase.storage.TaskState.SUCCESS) {
console.log('Success')
}
},
error => {
unsubscribe()
console.log("image upload failed" + error.toString())
},
() => {
firebase.storage()
.ref(`posts/images/${fileName}`)
.getDownloadURL()
.then((downloadUrl) => {
console.log(`file available at ${downloadUrl}`)
})
}
)
}
}
here a solution
const [image, setImage] = useState(null);
const [uploading, setUploading] = useState('')
useEffect(() => {
getPermission();
}, []);
const getPermission = async () => {
if (Platform.OS !== "web") {
const { status } =
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
}
};
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
const getPictureBlob = (uri) => {
// https://github.com/expo/expo/issues/2402#issuecomment-443726662
return 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", image, true);
xhr.send(null);
});
};
const uploadImageToBucket = async () => {
let blob;
try {
setUploading(true);
blob = await getPictureBlob(image);
const ref = await storage.ref().child(uuid.v4());
const snapshot = await ref.put(blob);
return await snapshot.ref.getDownloadURL();
} catch (e) {
alert(e.message);
} finally {
blob.close();
setUploading(false);
}
};