Im new to react native and Im working on a react native program, Im trying to run my code synchronously using useEffect, I tried to use await and promises but didn't work, this is how the code looks like
useEffect(() => {
dashBoard();
ret3();
}, []);
const [flag, setFlag] = useState(false);
const [within, setWitin] = useState(0);
const [above, setAbove] = useState(0);
const [under, setUnder] = useState(0);
const [bgArr, setBgArr] = useState([]);
const [lastBG, setLastBG] = useState(0);
const [lastBGtime, setLastBGtime] = useState('');
const [addBGlevel, setAddBGlevel] = useState(0);
const [startBG, setSBGP] = useState(0);
const [reason, setReason] = useState('');
//===========================Functions===============
const addBG = () => {
var time = new Date(); // Mon Jan 31 2022 23:07:59 GMT+0300 (+03)
var timeString = time.toString();
try {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO BGLevel (UserID, BGlevel, DateTime) VALUES (?,?,?)',
[222, addBGlevel, timeString],
);
console.log('inserted!!');
});
} catch (error) {
console.log(error);
}
if (addBGlevel <= 70) {
navigation.navigate('hypo');
} else if (addBGlevel > startBG) {
//startbgcorr =150
navigation.navigate('Calc');
}else if (reason == '1'){
navigation.navigate('Calc');
}
};
const dashBoard = async () => {
await retrieveDash2();
var w = 0;
var a = 0;
var u = 0;
for (let i = 0; i < bgArr.length; i++) {
if (bgArr[i] >= fromBGHome && bgArr[i] <= toBGHome) {
w++;
} else if (bgArr[i] > toBGHome) {
a++;
} else if (bgArr[i] < fromBGHome) {
u++;
}
}
var total = w + a + u;
var m = (a / total) * 100;
if (m >= 50) {
setFlag(true);
} else {
setFlag(false);
}
setWitin(w);
setAbove(a);
setUnder(u);
};
//==================================================
//===========================RETRIVE================
const retrieveDash = () => {
// insulinPen table
try {
db.transaction(tx => {
tx.executeSql(
'SELECT UserID, fromBG, toBG FROM patientprofile',
[],
(tx, results) => {
var rows = results.rows;
for (let i = 0; i < rows.length; i++) {
var userid = rows.item(i).UserID;
if (userid == 222) {
fromBGHome = rows.item(i).fromBG;
toBGHome = rows.item(i).toBG;
return;
}
}
},
);
});
} catch (error) {
console.log(error);
}
};
//==================================================
const retrieveDash2 = async () => {
await retrieveDash();
var time = new Date(); // Mon Jan 31 2022 23:07:59 GMT+0300 (+03)
var bgArr1 = [];
// insulinPen table
try {
db.transaction(tx => {
tx.executeSql(
'SELECT UserID, BGlevel, DateTime FROM BGLevel',
[],
(tx, results) => {
var rows = results.rows;
var lastString = rows.item(rows.length - 1).DateTime;
var d = new Date(lastString);
var momFormat = moment(d).format('yyyy/MM/DD hh:mm a');
setLastBGtime(momFormat);
setLastBG(rows.item(rows.length - 1).BGlevel);
for (let i = 0; i < rows.length; i++) {
var timeString = rows.item(i).DateTime;
var toObj = new Date(timeString);
var bgHome = rows.item(i).BGlevel;
var userid = rows.item(i).UserID;
console.log((time - toObj) / (1000 * 60 * 60));
if ((time - toObj) / (1000 * 60 * 60) <= 168) {
//168 is the last 7 days in hours
bgArr1.push(bgHome);
}
}
setBgArr(bgArr1);
console.log(bgArr1 + ' This is bg array');
console.log(
fromBGHome + ' ' + toBGHome + ' This is from and to',
);
},
);
});
} catch (error) {
console.log(error);
}
};
//==================================================
const ret3 = () => {
try {
db.transaction(tx => {
tx.executeSql(
'SELECT UserID startBG_correct FROM patientprofile',
[],
(tx, results) => {
var rows = results.rows;
for (let i = 0; i < rows.length; i++) {
var UID = rows.item(i).UserID;
if (UID == 222) {
var start = rows.item(i).startBG_correct;
setSBGP(start);
}
}
},
);
});
} catch (error) {
console.log(error);
}
};
and I want the functions to run before the interface is completely loaded so I used the following way
{bgArr.length > 0 && (within > 0 || above > 0 || under > 0) ? (
<PieChart
data={data}
width={widthScreen}
height={150}
chartConfig={chartConfig}
accessor={'population'}
backgroundColor={'#ECECEC'}
//absolute
/>
) : (
<ActivityIndicator size="large" />
)}
but it keeps loading and never show the interface until I run the program again
I need the code to work directly when loading the page in the following order
1-retrieveDash
2-retrieveDash2
3-dashBoard
Related
In the example code from the repository (https://github.com/wix/react-native-calendars/blob/master/example/src/screens/agendaScreen.tsx) the code is a little complicated and in class rendering.
I just want to simply add an event to a day (doesn't matter what date) as an example to continue. :)
This is the code I have (it just makes the agenda without any events) :
export default function App() {
const [items,setItems] = useState([]);
const timeToString = (time) => {
const date = new Date(time);
return date.toISOString().split('T')[0];
}
const loadItems = (day) => {
const items = items || {};
setTimeout(() => {
for (let i = -15; i < 85; i++) {
const time = day.timestamp + i * 24 * 60 * 60 * 1000;
const strTime = timeToString(time);
if (!items[strTime]) {
items[strTime] = [];
const numItems = Math.floor(Math.random() * 3 + 1);
for (let j = 0; j < numItems; j++) {
items[strTime].push({
name: 'Item for ' + strTime + ' #' + j,
height: Math.max(50, Math.floor(Math.random() * 150)),
day: strTime
});
}
}
}
const newItems = {};
Object.keys(items).forEach(key => {
newItems[key] = items[key];
});
setItems(newItems)
}, 1000);
}
return (
<View style={styles.container}>
<Agenda
items={items}
loadItemsForMonth={loadItems}
selected={'2017-05-16'}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
I am developing a "Battleship" game with two grids made up of divs and am currently attempting to add a click event listener to all of the divs.
The issue that I am having is that the event listener is being repeatedly triggered (until every single div has been clicked) when I refresh my page and I can't understand why...
Here's the event listener in question:
let aiGridCells = document.querySelectorAll(".ai-grid__game-cell");
aiGridCells.forEach(cell => {
cell.addEventListener("click", humanPlayer.humanAttack(cell.getAttribute('data-ai'),aiPlayer))
});
Where humanPlayer is an object that has been generated by a factory function:
const humanPlayer = playerFactory('human');
import gameboardFactory from './gameboardFactory';
const playerFactory = (name) => {
const playerBoard = gameboardFactory();
const humanAttack = (cell, player) => { // Where player is opponent
if (player.playerBoard.gameBoard[cell].id !== 'miss') {
player.playerBoard.receiveAttack(cell);
};
};
const aiAttack = (player) => { // Where player is opponent
const availableCells = [];
for (let i = 0; i < player.playerBoard.gameBoard.length; i++) {
if (player.playerBoard.gameBoard[i].id === null) {
availableCells.push(i);
};
};
const attackCell = Math.floor(Math.random() * availableCells.length);
player.playerBoard.receiveAttack(attackCell);
};
return {
name,
playerBoard,
humanAttack,
aiAttack
}
};
export default playerFactory;
and gameboardFactory is:
import shipFactory from './shipFactory';
const gameboardFactory = () => {
const gameBoard = [];
const shipYard = [];
const init = () => {
for (let i = 0; i<100; i++) {
gameBoard.push({id: null})
};
};
const checkValidCoordinates = (direction, start, end) => {
if (direction === 'horizontal') {
if ((start <= 9) && (end <= 9)) {
return true;
} else {
let newStart = (start/10).toString(10);
let newEnd = (end/10).toString(10);
if ((newStart.charAt(0)) === (newEnd.charAt(0))) {
return true;
};
};
} else {
if ((start <= 9) && (end <= 9)) {
return false
} else if (start <= 9) {
let newStart = start.toString(10);
let newEnd = end.toString(10);
if ((newStart.charAt(0)) === (newEnd.charAt(1))) {
return true;
};
} else {
let newStart = start.toString(10);
let newEnd = end.toString(10);
if ((newStart.charAt(1)) === (newEnd.charAt(1))) {
return true;
};
};
};
return false
};
const checkIfShipPresent = (direction, start, end) => {
if (direction === 'horizontal') {
for (let i = start; i <= end; i++) {
if (gameBoard[i].id !== null) {
return true;
}
};
return false;
} else {
for (let i = start; i <= end; i += 10) {
if (gameBoard[i].id !== null) {
return true;
}
};
return false;
};
};
const placeShip = (id, direction, start, end) => {
if (!checkValidCoordinates(direction, start, end)) {
return;
};
if (checkIfShipPresent(direction, start, end)) {
return;
};
const newShip = [];
if (direction === 'horizontal') {
for (let i = start; i <= end; i++) {
gameBoard[i].id = id;
newShip.push(i);
};
} else {
for (let i = start; i <= end; i += 10) {
gameBoard[i].id = id;
newShip.push(i);
};
};
shipYard.push(shipFactory(id, newShip));
};
const receiveAttack = (cell) => {
console.log(cell)
if (gameBoard[cell].id !== null) {
const attackedShip = shipYard.filter((ship) => {
return ship.id === gameBoard[cell].id;
})[0];
if (!attackedShip.hits.includes(cell)) {
attackedShip.hits.push(cell);
};
} else {
gameBoard[cell].id = 'miss';
};
};
const checkIfAllShipsSunk = () => {
let allShipsSunk = true;
shipYard.forEach((ship) => {
if (ship.isSunk() === false) {
allShipsSunk = false;
};
});
return allShipsSunk;
};
if (gameBoard.length === 0) {
init();
};
return {
gameBoard,
placeShip,
receiveAttack,
shipYard,
checkIfAllShipsSunk
};
};
export default gameboardFactory;
I'm completely lost to what the issue could be and have tried countless things to rectify it. Any suggestions would be hugely appreciated.
Thank you!
You trying to add actual function call as listener here:
let aiGridCells = document.querySelectorAll(".ai-grid__game-cell");
aiGridCells.forEach(cell => {
cell.addEventListener("click", humanPlayer.humanAttack(cell.getAttribute('data-ai'),aiPlayer))
});
So on your event listener initialization you actually call your function instead of passing it as a listener.
You can pass it like this instead:
aiGridCells.forEach(cell => {
cell.addEventListener("click", () => humanPlayer.humanAttack(cell.getAttribute('data-ai'),aiPlayer))
});
I am getting the following error when going to the URL.
Error: could not handle the request
I can not seem to figure out why. What did I do wrong?
Here is my index.js file.
const functions = require('firebase-functions');
var request = require('request');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest(async (req, res) => {
const itemDescription = req.query.itemDescription;
const pageNumber = req.query.pageNumber;
const categoryId = req.query.categoryId;
const sortBy = req.query.sortBy;
const narrowSearch = req.query.narrowSearch;
const typeOfListing = req.query.typeOfListing;
const sellerExclusions = req.query.sellerExclusions;
const tagsExclusions = req.query.tagsExclusions;
const country = req.query.country;
const minPrice = req.query.minPrice;
const maxPrice = req.query.maxPrice;
const entriesPerPage = req.query.entriesPerPage;
const buyingFormat = req.query.buyingFormat;
let operationName = "";
let entriesPerPage2 = "";
let sortOrder = "";
let currentPage = "";
if (pageNumber !== null) {
currentPage = pageNumber;
} else {
currentPage = 1;
}
if (typeOfListing === 'active') {
operationName = "findItemsAdvanced";
entriesPerPage2 = 50;
} else {
operationName = "findCompletedItems";
if (buyingFormat === "Auction") {
entriesPerPage2 = 50;
} else {
entriesPerPage2 = 25;
}
}
let apicall = "https://URL?";
if (typeOfListing === "active") {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "BestMatch";
sortOrder = "BestMatch";
}
} else {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "EndTimeSoonest";
sortOrder = "EndTimeSoonest";
}
}
if (categoryId !== null) {
apicall += "&categoryId=";
apicall += categoryId;
}
apicall += "&paginationInput.pageNumber=";
apicall += currentPage;
apicall += "&keywords=";
apicall += itemDescription;
apicall += "&paginationInput.entriesPerPage=" + entriesPerPage2;
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
request(apicall, function (error, response, body) {
if (!error && response.statusCode === 200) {
//here put what you want to do with the request
let paginationOutput = JSON.parse(body).findCompletedItemsResponse[0].paginationOutput;
let pageNumber = null;
let totalPages = null;
let totalEntries = null;
let totalInPage = null;
for (i = 0; i < paginationOutput.length; i++) {
pageNumber = paginationOutput[i].pageNumber[0];
totalPages = paginationOutput[i].totalPages[0];
totalEntries = paginationOutput[i].totalEntries[0];
totalInPage = paginationOutput[i].entriesPerPage[0];
}
let items = JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item;
let itemId = null;
let title = null;
let categoryId = null;
let categoryName = null;
let galleryURL = null;
let link = null;
let dateEnded = null;
let watchCount = null;
let bestOfferEnabled = null;
let listingType = null;
let soldForOriginal = null;
let timeLeft = null;
let dateLeft = null;
let bidCount = null;
let shipping = null;
//TODO
let soldForBestOffer = null;
var itemArray = {
result: []
};
for (i = 0; i < items.length; i++) {
itemId = items[i].itemId[0];
title = items[i].title[0];
galleryURL = items[i].galleryURL[0];
link = items[i].viewItemURL[0];
category = items[i].primaryCategory;
for (j = 0; j < category.length; j++) {
categoryName = category[j].categoryName[0];
categoryId = category[j].categoryId[0];
}
listingInfo = items[i].listingInfo;
for (k = 0; k < listingInfo.length; k++) {
watchCount = listingInfo[k].watchCount === undefined ? "0" : listingInfo[k].watchCount[0];
bestOfferEnabled = listingInfo[k].bestOfferEnabled[0];
listingType = listingInfo[k].listingType[0];
dateLeft = listingInfo[k].endTime[0];
}
sellingStatus = items[i].sellingStatus;
for (jj = 0; jj < sellingStatus.length; jj++) {
soldForOriginal = sellingStatus[jj].convertedCurrentPrice[0].__value__;
bidCount = sellingStatus[jj].bidCount === undefined ? "0" : sellingStatus[jj].bidCount[0];
timeLeft = sellingStatus[jj].timeLeft === undefined ? "-" : sellingStatus[jj].timeLeft[0];
}
shippingInfo = items[i].shippingInfo;
for (ii = 0; ii < shippingInfo.length; ii++) {
shipping = shippingInfo[ii].shippingServiceCost === undefined ? "0.0" : shippingInfo[ii].shippingServiceCost[0];
shippingType = shippingInfo[ii].shippingType[0];
if (shipping === "0.0") {
shipping = "0.00"
}
if (shippingType === 'Calculated') {
shipping = "TBD";
} else {
if (shipping === '0.00') {
shipping = "FREE";
}
}
}
itemArray.result.push({
"itemId": itemId,
"title": title,
"galleryURL": galleryURL,
"link": link,
"categoryName": categoryName,
"categoryId": categoryId,
"bidCount": bidCount,
"dateEnded": dateLeft,
"watchCount": watchCount,
"bestOfferEnabled": bestOfferEnabled,
"listingType": listingType,
"timeLeft": timeLeft,
"soldForOriginal": soldForOriginal
});
}
res.json({
ack: "success",
message: "results found",
currentPage: pageNumber,
totalPages: totalPages,
totalEntries: totalEntries,
totalInPage: totalInPage,
results: itemArray.result,
searchResult: JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item
});
} else {
res.json({
error: "didnt work"
});
}
})
});
In Cloud Functions you need to manage asynchronous method calls via Promises. request supports callback interfaces natively but does not return a promise.
You should use another library, like axios, along the following lines:
exports.addMessage = functions.https.onRequest(async (req, res) => {
try {
// ...
let apicall = "https://URL?";
// ...
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
const response = await axios.get(apicall);
// handle success
// ...
res.json({..});
} catch (error) {
res.status(500).send({ 'error': error });
}
});
Note that you probably need to be on the "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)
Also note that request is deprecated.
I use the the variable previous_epoch to fetch reddit posts before today in the first iteration. The next iteration previous_epoch must contain the date from the response data. Oddly enough, the date doesn't change after the first two loops
const getposts = async(user) => {
var dataArray = [];
var utc = new Date()
.toJSON()
.slice(0, 10)
.replace(/-/g, "/");
var previous_epoch;
for(let i=0; i <=5; i++) {
if(i == 0) {
console.log('i is 0');
previous_epoch = new Date(utc).getTime() / 1000;
console.log('p',previous_epoch); <--keeps doesn't work after second loop
}
else {
// console.log('else',dataArray);
previous_epoch = dataArray[dataArray.length-1].created_utc
console.log('else',previous_epoch);
}
await getdat(user,previous_epoch).then((resp) => {
let jsondat = resp.data.data;
dataArray = jsondat.concat(dataArray);
})
}
// console.log( dataArray);
var result = _.map( dataArray, function( o ) {
return o.id;
});
/* console.log("%j",result); */
}
Function getdat()
const getdat = (user,epoch) => {
const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
console.log('elZK',sub_url);
return new Promise((resolve, reject) => {
axios.get(sub_url)
.then(response => {
return resolve(response)
})
.catch(error => {
return reject(error.message)
})
})
}
here is the fiddle
EDIT 2:
I've changed the logic so that I get the next date from getdat function itself
const getdat = (user,epoch) => {
let res= {};
const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=300&sort=desc&before=${epoch}`;
console.log('elZK',sub_url);
return new Promise((resolve, reject) => {
axios.get(sub_url)
.then(response => {
let d = response.data.data;
let e = d[d.length - 1].created_utc;
console.log('e',e);
res.data = d;
res.epoch = e;
return resolve(res)
})
.catch(error => {
return reject(error.message)
})
})
}
export const getUserPosts = async(user) => {
var dataArray = [];
var utc = new Date()
.toJSON()
.slice(0, 10)
.replace(/-/g, "/");
var previous_epoch;
var epoch;
for(let i=0; i <=5; i++) {
if(dataArray.length === 0) {
console.log('i is 0');
previous_epoch = new Date(utc).getTime() / 1000;
console.log('p',previous_epoch);
}
else {
// console.log('else',dataArray);
previous_epoch = epoch;
console.log('else',previous_epoch);
}
const resp = await getdat(user,previous_epoch);
const jsondat = resp.data;
dataArray = jsondat.concat(dataArray);
epoch = resp.epoch;
}
// console.log( dataArray);
var result = _.map( dataArray, function( o ) {
return o.id;
});
console.log("%j",result);
}
On first iteration you fetch posts before today, so last post in result will have created_utc before or equal today. Next iterations just repeat you first request.
Try this code
for(let i=0; i <=5; i++) {
if(dataArray.length === 0) {
console.log('i is 0');
previous_epoch = new Date(utc).getTime() / 1000;
console.log('p',previous_epoch);
}
else {
// console.log('else',dataArray);
previous_epoch = dataArray[0].created_utc
console.log('else',previous_epoch);
}
const resp = await getdat(user,previous_epoch);
const jsondat = resp.data.data;
dataArray = jsondat.concat(dataArray);
}
Try this code
const getdat = (user,epoch) => {
const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=10&sort=desc&before=${epoch}`;
console.log('elZK',sub_url);
return axios.get(sub_url);
};
const getposts = async(user) => {
let dataArray = [];
let previous_epoch;
for(let i=0; i <=5; i++) {
previous_epoch = dataArray.length>0 ? dataArray[dataArray.length-1].created_utc-1 : Math.floor(Date.now()/1000);
const result = await getdat(user,previous_epoch);
dataArray = dataArray.concat(result.data.data);
}
console.log(dataArray.map(e => e.created_utc));
};
getposts('data');
I'm making a request to an API for prices of a cryptocurrency for a date range & storing the result in an array. The goal is to populate a line graph with those prices when the page loads but I can't figure out for the life of my why pricesArr prints when I console.log it but if I try this.setState({dataArr: pricesArr}) then I get an TypeError: Cannot read property 'setState' of undefined.
The object in pricesArr prints in the console and looks like this:
[{USD: 7629.4, EUR: 6503.14}, {USD: 6754.4, EUR: 5432.14} ... ]
class App extends Component {
constructor(props) {
super(props);
this.state = {
dataArr:[]
}
}
getData(){
var url = 'https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD,EUR&ts='
let pricesArr = []
for (let i=1; i <= 30; i++) {
const num = i.toString()
const date = new Date('2018.06.' + num)
const unixTimestamp = date / 1000
const api_url = url + unixTimestamp
if (i % 5 === 0 || i === 1) {
axios.get(api_url)
.then(res => {
var obj = res.data['BTC']
pricesArr.push(obj)
})
}
}
this.setState({dataArr: pricesArr})
}
componentDidMount () {
this.getData()
}
render() {
return (
<div>
Hi
</div>
);
}
}
export default App;
Strange that your this is undefined. try this.
getData = () => {
var url = 'https://min-api.cryptocompare.com/data/pricehistorical?fsym=BTC&tsyms=USD,EUR&ts='
let pricesArr = []
for (let i=1; i <= 30; i++) {
const num = i.toString()
const date = new Date('2018.06.' + num)
const unixTimestamp = date / 1000
const api_url = url + unixTimestamp
if (i % 5 === 0 || i === 1) {
axios.get(api_url)
.then(res => {
var obj = res.data['BTC']
pricesArr.push(obj)
})
}
}
this.setState({dataArr: pricesArr})
}