Store geolocation coordinates as a const variable react - reactjs

im a little stuck. Im trying to store the user coordinates from the componentDidMount in the handlesubmit as a const however whenever i try to I'll get an error. The error i'm getting is :
'position' is not defined no-undef.
Any way i could go about storing the position as a const so i could access it in the handlesubmit part?
Thanks
Code is below
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(pos ) {
const { latitude, longitude } = pos.coords;
console.log(pos )
console.log(latitude)
console.log(longitude)
});
}
handleSubmit = (event) => {
const pName = document.querySelector('#pName') .value.trim();
const pCondition = document.querySelector('#pCondition') .value.trim();
const pDescription = document.querySelector('#pDescription') .value.trim();
const pLocation = position
console.log(pLocation )
const post = 'pName=' + encodeURIComponent(pName) + '&pCondition=' + encodeURIComponent(pCondition) + '&pDescription=' + encodeURIComponent(pDescription);
alert('A form was submitted: ' + data);
fetch('api url', {
method: 'POST',
mode: "no-cors",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
// body: JSON.stringify(this.state)
body: post
}).then(function(response) {
console.log(response.text)
/*return response.json();*/
});
event.preventDefault();
}

Its simple
const getPosition = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
getPosition()
.then(position => {
console.log(position);
sessionStorage.setItem('position', position);
)
.catch(error => {
console.error(error);
}
Use the variable position in the sessionStorage:
const data = sessionStorage.getItem('position');
Or you can use useState

const getPosition = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
}
getPosition()
.then(position => {
console.log(position);
sessionStorage.setItem('position', position);
)
.catch(error => {
console.error(error);
}

Related

dataLoaded state only changed after page reloaded

I'm doing an API call to get some data. then I keep a useState called dataLoaded. on a successful API call I make the dataLoaded=true. but to see it changed I have to reload the page.
following is my code.
const [dataLoaded, setDataLoaded] = useState(false)
useEffect(() =>{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/movie/`+ path.eventId + `/venue/`+ path.venue +`/showtime`;
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions());
const json = await response.json();
// console.log(json);
// console.log(json.data.venueDateShowtime)
setShowTimes(json.data.dateShowtimes[0].showtimes[0]);
console.log(json.data.dateShowtimes[0].date)
setShowdate(json.data.dateShowtimes[0].date);
setDataLoaded(true);
console.log(dataLoaded)
console.log(showTimes.showtimeId)
console.log(showdate)
if(dataLoaded){
getSeatsArrangement();
}
console.log('jjjj')
}
catch (error) {
console.log("error",error);
}
};
fetchData();
},[]);
const getSeatsArrangement = async () => {
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
console.log(showTimes.showtimeId)
console.log(showdate)
try{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/seat?venueId=` + path.venue + `&movieId=`+ path.eventId +`&showtimeId=1011&movieDate=2022-10-11`;
const response = await fetch(url,requestOptions());
const json = await response.json();
console.log(json)
setReservedSeats(json.data.reservedSeats.reservedSeat)
setNonReservedSeats(json.data.reservedSeats.nonReservedSeats)
console.log(reservedSeats)
console.log(nonReservedSeats)
} catch(error) {
console.log("error",error);
}
}
Console logs when page loads
What is the aim of the code? fetchData is performed once after page loading (because of using ,[] at the end of useeffect.
And a remark: If you log your state right after setting it, the previous value will be shown! you should define another useeffect with your state as dependency (for each state) and log your state in there.
useEffect(() => {
console.log(dataLoaded)
if(dataLoaded){
getSeatsArrangement();
}
console.log('jjjj')
}, [dataLoaded]);
useEffect(() => {
console.log(showTimes.showtimeId)
}, [showTimes]);
useEffect(() => {
console.log(showdate)
}, [showdate]);
useEffect(() =>{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/movie/`+ path.eventId + `/venue/`+ path.venue +`/showtime`;
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions());
const json = await response.json();
// console.log(json);
// console.log(json.data.venueDateShowtime)
setShowTimes(json.data.dateShowtimes[0].showtimes[0]);
console.log(json.data.dateShowtimes[0].date)
setShowdate(json.data.dateShowtimes[0].date);
setDataLoaded(true);
}
catch (error) {
console.log("error",error);
}
};
fetchData();
},[]);

async function in react component isn't working when triggered from the axios request

network.services.js
axiosCall = (axiosURL) => {
// const axiosURL = "https://api.github.com/user"
axios.get(axiosURL, {
headers: {
'Authorization': `qwdvryjutmnevw`,
}
}).then((res) => {
console.log(res.data);
return res.data;
}).catch((error) => {
throw error.message;
// console.error(error);
// toast.error(error.message);
})
}
component.js
const getData = async () => {
const asyncExample = async () => {
const result = await networkServices.axiosCall("/api/v1/calendars");
const responseData = await result;
console.log(responseData);
return responseData;
}
const data = asyncExample()
data.then(function(result) {
console.log(result); // "Some User token"
})
}
Trying to get data from service to my component in const result, console form service is consoling data but component is always returning undefined instead of data from the service file. SetTimeout function is also not working in component.
You have many mistakes. I advise you to take a look at documentation about Promises
First one:
You don't return data in axiosCall
A way to return data:
axiosCall = (axiosURL) => new Promise((resolve, reject) => {
axios.get(axiosURL, {
headers: {
'Authorization': `yourTokenHere`,
}
}).then((res) => {
// return a response data
resolve(res.data);
}).catch((error) => {
// return only error message
reject(error.message);
})
})
to use axiosCall:
try {
// don't forgot to configure axios with base url
const data = await axiosCall('/api/v1/calendars');
// do something with your data
} catch (e) {
// do something with error message
console.log(e);
}
Second:
Your make mistakes when call async function
Look at this example:
const getData = () => {
networkServices
.axiosCall("/api/v1/calendars")
.then(function(result) {
// when promise resolve
console.log(result);
})
.catch(error => {
// when promise reject
console.log(error)
})
}

How to update state object in useEffect

How to update state object in useEffect
Hi All,
In my React app I am calling an online service in order to get some WIFI information. Eventually, I would like to show\render the information of the wifiData to the user.
const [macAddress, setMacAddress] = useState('');
const [wifiData, setwifiData] = useState({});
const axios = require("axios");
const ClientOAuth2 = require('client-oauth2')
const clientAuth = new ClientOAuth2({
accessTokenUri: 'https:....',
clientId: '....',
clientSecret: '....',
scopes: ['....']
})
const wifiService = useCallback(() => {
clientAuth.credentials.getToken().then(function (user) {
if (user.accessToken) {
axios({
method: "post",
url: "....access_token=" + user.accessToken,
data: {
....,
},
}).then(function (response) {
// setwifiData ??
console.log(response.data)
}).catch(function (error) {
console.log(error);
});
}
})
}, [axios, clientAuth.credentials, macAddress])
useEffect(() => {
if (!openDrawer && macAddress !== "") {
wifiService();
// setwifiData ??
}
}, [wifiService, clientAuth.credentials, openDrawer, macAddress]);
return (
<div style={{ padding: 20 }}>
// render wifiData
)
How can I store the response data in wifiData ?
What is the proper way to deal with this type of scenario? I couldn’t figure it out.
Appreciate the help
Thank you
Set the state inside wifiService():
const wifiService = useCallback(() => {
clientAuth.credentials.getToken().then(function (user) {
if (user.accessToken) {
axios({
method: "post",
url: "....access_token=" + user.accessToken,
data: {
....,
},
}).then(function (response) {
// ** put response in correct format here if you need to
setwifiData(response)
console.log(response.data)
}).catch(function (error) {
console.log(error);
});
}
})
}, [axios, clientAuth.credentials, macAddress])
Remove wifiService from useEffect triggers to prevent infinite loop:
useEffect(() => {
if (!openDrawer && macAddress !== "") {
wifiService();
}
}, [clientAuth.credentials, openDrawer, macAddress]);

Picking up document/Images from mobile device and show them into a list in react native

I am using react native document picker library to upload documents to the server my code is working perfectly but the issue is i want to show list of these selected images/documents i am not sure how to perform that action here is my code....
Document Selection code:
pickMultiple() {
try {
DocumentPicker.pickMultiple({
})
.then(images => {
this.setState({
image: null,
images: images
});
//console.log(images.length);
})
.catch(e => alert(e));
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
}
Form Uploading code:
SubmitProposal = async () => {
const Uid = await AsyncStorage.getItem("projectUid");
const { params } = this.props.navigation.state;
const { amount, Description, DurationListKnown, images } = this.state;
console.log(
amount,
Description,
DurationListKnown[0],
images,
params.job_id,
images.length,
Uid
);
const formData = new FormData();
formData.append('user_id' , Uid);
formData.append('project_id' , params.job_id);
formData.append('proposed_amount' , amount);
formData.append('proposed_time' , DurationListKnown[0]);
formData.append('proposed_content' , Description);
formData.append('size' , images.length);
//formData.append('proposal_files' , images);
images.forEach((item, i) => {
// propertyData.description = this.props.description
var path = item.uri;
// var filename = path.substring(path.lastIndexOf('/')+1);
var filename = item.name;
formData.append("proposal_files"+i, {
uri: path,
type: item.type,
name: filename || `filename${i}.jpg`,
});
});
console.log(formData);
fetch('https://...proposal/add_proposal',{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(response => {
if (response.status == "200") {
console.log(response);
this.showSuccessAlert();
} else if (response.status == "203") {
console.log(response);
this.showAlert();
}
}).catch((error) => {
console.log(JSON.stringify( error));
});
};
kindly help me about how can i show list of these images/documents

How to perform a two callback functionality?

I am using the cloudinary api with REACT/AXIOS and was wondering how I could pull data before the axios call and also after. My problem I am having is that if I use one callback I can only put the one or the other data. So is it possible to use two callbacks and if so how would you do so?
Or should I go about this a different way?
What I want is to pull the progression of the upload out and be able to store that value to the state. My only problem is that I am not sure of the correct way to do this? I need to do it inside the onUploadProgress fucntion.
Here is the code:
Function in component:
uploadImage(files) {
const image = files[0];
const cloudName = 'hyszj0vmt';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
const apiSecret = '***********';
const uploadPreset = '**************';
const timestamp = Date.now() / 1000;
const paramStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}${apiSecret}`;
const signature = sha1(paramStr);
const params = {
api_key: '*******',
timestamp: timestamp,
upload_preset: uploadPreset,
signature: signature
};
APIManager.upload(url, image, params, (err, response) => {
if (err) {
console.log(`UPLOAD ERROR: ${err}`);
return;
}
const imageUrl = response['secure_url'];
let updatedProfile = Object.assign({}, this.state.updated);
updatedProfile['image'] = imageUrl;
this.setState({
updated: updatedProfile
});
});
}
APIManager function:
upload: (endpoint, file, params, callback) => {
let fd = new FormData();
fd.append('file', file);
Object.keys(params).forEach(key => {
fd.append(key, params[key]);
});
const config = {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
onUploadProgress: progressEvent => {
const progress = Math.round(
progressEvent.loaded * 100.0 / progressEvent.total
);
console.log(progress + '%');
}
};
axios
.post(endpoint, fd, config)
.then(response => {
const { data } = response;
callback(null, data);
})
.catch(err => {
callback(err, null);
});
}
};
How about this?
upload: (endpoint, file, params, callback, callbackProgress) => {
...
const config = {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
onUploadProgress: progressEvent => {
const progress = Math.round(
progressEvent.loaded * 100.0 / progressEvent.total
);
callbackProgress(progress);
}
};
...
});
Usage:
APIManager.upload(url, image, params, (err, response) => {
...
}, (progress) => {
console.log(progress);
});

Resources