I can't figure out what is preventing line wrapping - javascript

I have a script when using the library typed.js . I'm trying to output 3 lines + 1 final one. The code works by outputting 2 lines + 1 final one. When trying to fix it, the code freezes without sending an error.
This version of the code works without errors. Outputs 2 lines + 1.
const lineNumber = app.id !== 2 ? ++app.id : (app.id += 2);
setTimeout(() => {
const typed = new Typed(`#line${lineNumber}`, {
strings: text,
typeSpeed: speed,
onComplete: callback,
});
}, timeout);
};
$.getJSON(ipgeolocation, (data) => {
writeLine(["line1"], 30, () => {
if (app.skippedIntro) return;
clearCursor();
const usernames = ['user', 'dude'];
const ip = data.ip ? data.ip : usernames[Math.floor(Math.random() * usernames.length)];
const country = data.country_name ? data.country_name : 'your country';
writeLine([`line2`], 30, 500, () => {
if (app.skippedIntro) return;
clearCursor();
writeLine([`start`], 120, 500, () => {
timeouts.push(
setTimeout(() => {
if (app.skippedIntro) return;
clearCursor();
setTimeout(() => {
skipIntro();
}, 500);
}, 1000)
);
});
});
});
});
This version of the code does not work. According to the idea, it should output 3 lines + 1.
1.
const lineNumber = app.id !== 2 ? ++app.id : (app.id += 2);
setTimeout(() => {
const typed = new Typed(`#line${lineNumber}`, {
strings: text,
typeSpeed: speed,
onComplete: callback,
});
}, timeout);
};
$.getJSON(ipgeolocation, (data) => {
writeLine(["line1"], 30, () => {
if (app.skippedIntro) return;
clearCursor();
const usernames = ['user', 'dude'];
const ip = data.ip ? data.ip : usernames[Math.floor(Math.random() * usernames.length)];
const country = data.country_name ? data.country_name : 'your country';
writeLine([`line2`], 30, 500, () => {
if (app.skippedIntro) return;
clearCursor();
writeLine([`line3`], 30, 500, () => {
if (app.skippedIntro) return;
clearCursor();
writeLine([`start`], 120, 500, () => {
timeouts.push(
setTimeout(() => {
if (app.skippedIntro) return;
clearCursor();
setTimeout(() => {
skipIntro();
}, 500);
}, 1000)
);
});
});
});
});
});

We have the main bands and when you get 3, you need to add 2 to learn the 5th.
const lineNumber = app.id !== 3 ? ++app.id : (app.id += 2);

Related

RTK query useQuery invalidateTags on infinity scroll

I have this function that basically helps me implement infinite scroll everywhere. Still, I faced a problem where when I invalidate a tag related to an endless scroll tag it doesn't update the needed portion because of the offset and limit parameters.
The way I provide tags:
providesTags: (item) => item?.result
? [...item.result.departures.map(({ ID }) => ({
type: 'Departures',
id: ID,
})),
{ type: 'Departures', id: 'LIST' },
]
: [{ type: 'TransitDepartures', id: 'LIST' }],
To Invalidate tags I use invalidatesTags
The function I described
export const isValidNotEmptyArray = (array) =>
!!(array && array?.length && array?.length > 0)
const useFetchQuery = (
useGetDataListQuery,
{ offset = 0, limit = 10, ...queryParameters },
filter = () => true,
) => {
const [localOffset, setLocalOffset] = useState(offset)
const [combinedData, setCombinedData] = useState([])
const [gotWiped, setGotWiped] = useState(0)
const queryResponse = useGetDataListQuery(
{
offset: localOffset,
limit,
...queryParameters,
},
)
const { data: fetchData = { result: [], total: 0 } } = queryResponse || {}
const total = useMemo(() => fetchData.total, [fetchData])
useEffect(() => {
const value = departure ? fetchData.result.departures : fetchData.result
if (isValidNotEmptyArray(value)) {
setGotWiped(0)
if (localOffset === 0 || !localOffset) {
setCombinedData(value)
} else {
setCombinedData((previousData) => [...previousData, ...value])
}
} else if (gotWiped === 0) {
setGotWiped(1)
}
}, [fetchData])
useEffect(() => {
if (gotWiped) {
setCombinedData([])
}
}, [gotWiped])
const refresh = () => {
setLocalOffset((prev) => (prev === 0 ? null : 0))
setCombinedData([])
}
const loadMore = () => {
if (combinedData.length < total) {
setLocalOffset(combinedData.length)
}
}
return {
data: useMemo(() => combinedData.filter(filter), [combinedData, filter]),
offset: localOffset,
total:
combinedData.length > combinedData.filter(filter).length
? combinedData.filter(filter).length
: total,
loadMore,
refresh,
isLoading: queryResponse?.isLoading,
isFetching: queryResponse?.isFetching,
}
}

Handle all promise rejections in nested promises? [duplicate]

This question already has an answer here:
Weird behavior with Promise throwing "Unhandled promise rejection" error
(1 answer)
Closed 8 months ago.
I'm using Promise.race so I can time out the fetch call. During a test to an API endpoint that doesn't exist, I'm getting an "Unhandled promise rejection" error. The code is supposed to console.log once upon any failure. Where am I not handling the promise rejection? FYI the main function is function Retrieve
window.path = "http://localhost:3000/records";
function isPrimary(color) {
let colorIsPrimary = false;
(color.startsWith("red") || color.startsWith("blue") || color.startsWith("yellow")) ? colorIsPrimary = true : null;
return colorIsPrimary;
}
function transformData(records,page) {
const transformedData = {
"ids" : [],
"open": [],
"closedPrimaryCount": 0,
"previousPage": null,
"nextPage": null
}
let closedPrimaryCount = 0;
records.forEach((record, index) => {
if (index < 10) {
transformedData.ids.push(record.id);
record["isPrimary"] = false;
isPrimary(record.color) ? record.isPrimary = true : null;
record.disposition == "open" ? transformedData.open.push(record) : null;
if (record.disposition == "closed") {
isPrimary(record.color) ? closedPrimaryCount++ : null;
}
}
})
transformedData.closedPrimaryCount = closedPrimaryCount;
let previousPage = null;
page > 1 ? previousPage = page - 1 : null;
transformedData.previousPage = previousPage;
let nextPage = null;
records.length > 10 ? nextPage = page + 1 : null;
transformedData.nextPage = nextPage;
return transformedData;
}
function promiseTimeout(promise, ms) {
let timeout = new Promise((resolve, reject) => {
let timeoutID = setTimeout(() => {
clearTimeout(timeoutID);
reject("fetch failed - timeout");
}, ms)
})
return Promise.race([promise, timeout]);
}
function doFetch(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((response) => {
if (!response.ok) {
reject(new Error("fetch failed - non 200"));
}
response.json()
.then((records) => {
resolve(records);
})
.catch((error) => {
reject(new Error("fetch failed - error from response.json"));
})
})
.catch((error) => {
reject(new Error("fetch failed - error from fetch"));
})
})
}
function retrieve({page = 1, colors = ["red", "brown", "blue", "yellow", "green"], thetest = false, windowPath = window.path} = {}) {
return new Promise((resolve,reject)=>{
!thetest ? windowPath = "http://localhost:3000/records" : null;
// limit set to 11 so we can determine nextPage
const limit = "11";
const offset = "" + ((page * 10) - 10);
let colorArgs = "";
colors.forEach((color, index) => {
colorArgs = colorArgs + "&color[]=" + color;
});
const requestQuery = `limit=${limit}&offset=${offset}${colorArgs}`;
const requestURL = new URI(windowPath);
requestURL.query(requestQuery);
const promiseRace = promiseTimeout(doFetch(requestURL.toString()), 4000);
promiseRace.then((records) => {
const transformedData = transformData(records, page);
resolve(transformedData);
})
promiseRace.catch((error) => {
console.log(error);
})
});
};
export default retrieve;
After ggorlen's excellent advice, I refactored to this much cleaner (and test-passing) code:
async function getTransformedData(url,page) {
try {
const response = await fetch(url);
if (response.ok) {
const records = await response.json();
const transformedData = transformData(records,page);
return(transformedData);
} else {
throw new Error("failed");
}
}
catch(error) {
console.log(error);
}
// getTransformedData
}
function retrieve({page = 1, colors = ["red", "brown", "blue", "yellow", "green"]} = {}) {
// limit set to 11 so we can determine nextPage
const limit = "11";
const offset = "" + ((page * 10) - 10);
let colorArgs = "";
colors.forEach((color, index) => {
colorArgs = colorArgs + "&color[]=" + color;
});
const requestQuery = `limit=${limit}&offset=${offset}${colorArgs}`;
const requestURL = new URI(window.path);
requestURL.query(requestQuery);
return getTransformedData(requestURL.toString(),page);
};

Why this setInterval is executing multiple times?

I have the below code in a vue application
mounted: function () {
this.timer = setInterval(async () => {
if (this.progress >= 1) {
this.progress = 1
clearInterval(this.timer)
}
console.log('update')
const id = this.$route.params.id
const progOut = await this.api.get(`/api/mu/job/${id}/status`)
const response = progOut.data
this.progress = response.data.progress / 100
this.state = response.data.status
}, 7000)
},
I was expecting it to execute the get request every 7 seconds but it is executing the call every 500ms approx
I read other answers and so far I think this is the proper way but the code is executing too many requests
What is the proper way to call a function from within the setInterval to make it actually wait the timeout?
Edit: This was my final code in case someone goes through the same
methods: {
redirect (page) {
if (page === 'FINISHED') {
this.$router.push({
name: 'viewReport',
params: { id: 4 }
})
} else {
this.$router.push({
name: 'errorOnReport',
params: { id: 13 }
})
}
}
},
watch: {
state: async function (newVal, old) {
console.log('old ' + old + ' newVal ' + newVal)
if (newVal === 'FAILED' || newVal === 'FINISHED') {
this.redirect(newVal)
}
}
},
data () {
return {
state: null,
timer: null,
progress: 0.0,
progressStr: '0%'
}
},
mounted () {
const update = async () => {
if (this.progress >= 1) {
this.progress = 1
}
console.log('update ' + new Date())
const id = this.$route.params.id
const progOut = await this.api.get(`/api/mu/job/${id}/status`)
const response = progOut.data
this.state = response.data.status
this.progress = response.data.progress / 100
this.progressStr = response.data.progress + '%'
}
update()
this.timer = setInterval(update, 10000)
},
beforeUnmount () {
clearInterval(this.timer)
}
A better design is to wrap setTimeout with a promise, and do the polling in an async method that loops...
mounted: function() {
this.continuePolling = true; // suggestion: we have to stop sometime. consider adding continuePolling to data
this.poll();
},
unmounted: function() { // almost the latest possible stop
this.continuePolling = false;
},
methods:
async poll(interval) {
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
while(this.continuePolling) {
await this.updateProgress();
await delay(7000);
}
},
async updateProgress() {
const id = this.$route.params.id
const progOut = await this.api.get(`/api/mu/job/${id}/status`)
const result = progOut.data.data;
this.progress = result.progress / 100
this.state = result.status
}

Camera Plugin not opening camera in Ionic 4

I am working on a project in Ionic 4.
I would like user to upload picture by capturing from camera or uploading from library. For now I am running in development mode. The problem is that I am not being able to open camera or photo library on device in debugging mode. However the camera is opening when I run on "DEVAPP". I have tried taking permission but nothing is working out. Here is my code, tried many ways therefore code is a bit scattered:
async selectImage() {
try {
const actionSheet = await this.actionSheetController.create({
header: 'Select Image source',
buttons: [{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
await actionSheet.present();
} catch (error) {
alert(error);
}
}
takePicture(sourceType: PictureSourceType) {
const options: CameraOptions = {
quality: 100,
sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
alert('i m n takepicture');
this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.CAMERA]).then(
result => console.log('i am asking for permision: ' + result),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA)
);
if (this.camera.PictureSourceType.CAMERA) {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA).then(
result =>
this.camera.getPicture(options).then(imagePath => {
if (this.plt.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
const correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
const currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}). catch((error) => {
console.warn('error: ' + error);
});
} else {
const currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
const correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.CAMERA));
} else {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.PHOTOLIBRARY).then(
result =>
this.camera.getPicture(options).then(imagePath => {
if (this.plt.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
const correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
const currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
} else {
const currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
const correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.PHOTOLIBRARY));
}
}
Try this
takePicture(sourceType: PictureSourceType) {
const options: CameraOptions = {
quality: 100,
sourceType:sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then(
imageData => {
///DO YOUR LOGIC
},
err => {
// Handle error
}
);
}

When i use search by symbols i have a problem, why get request send by any symbols?

searchEmployee(e) {
const {entityType} = this.state;
const searchText = this.searchInput.value;
if (e.target.value !== '' && searchText.length !== 0) {
this.drop.hide();
if (searchText.length > 3) {
this.timeout = setTimeout(() => {
this.setState({
showSearchLoader: true,
result: [],
resultCounts: [],
hasMoreItems: false,
searchResultsEmpty: false,
entityType: 10,
searchAll: true
});
this.getResults(searchText, entityType, this.searchResultsCount, 0, false);
}, 1000);
}
}
}
getResults(searchText, entityType, searchResultsCount, offset, concat = true) {
const {result: stateResult} = this.state;
searchGlobal(searchText, entityType, searchResultsCount, offset).then(({result, resultCounts}) => {
this.setState({
result: concat ? _.concat(stateResult, result) : result,
resultCounts,
offset: offset,
hasMoreItems: result.length >= 8,
showSearchLoader: false,
searchResultsEmpty: !result.length
});
this.searchInput.focus();
setTimeout(() => this.drop.show(), 400);
}).catch(handleErrorResponse);
}
get request
When i print in timeout time two or more symbols i have - two or more request!
And this request back to me error!
It turns out from one that returns data from another avatar, how to make such a request that he would not send each character but only what will be printed at the end

Categories