How figure out calling function setTimeout function at react - javascript

i have a react functional component.
Here is i have getData function, with this function i'm getting some data from api and then if data have i wan't to call anotherFunc();, But i wan't to do that after 3 second. I tried to put there setTimeout function but it's worked directly not wait 3 second. What i need to do?
function Hello(props) {
anotherFunc = () => {
console.log('hello');
}
const getData = () => {
let data = {
id: 1
}
axios.post(baseUrl, data).then(res => {
if (res.data) {
setTimeout(() => {
anotherFunc();
}, 3000);
}
});
}
return <h1>Something</h1>;
}
export default Hello;

Related

Trying to execute an imported Async function but the function is not behaving asynchronously

I am using React to build a website. I have imported an asynchronous function to execute when I press a button. However, the function is not working asynchronously and I really don't understand why.
interact.js:
export const getNFT = async () => {
setTimeout(() => {
console.log('getNFT code execute');
return nft;
}, 2000);
};
const nft = {
tokenURI: 'https://gateway.pinata.cloud/ipfs/QmdxQFWzBJmtSvrJXp75UNUaoVMDH49g43WsL1YEyb',
imageURL: 'https://gateway.pinata.cloud/ipfs/QmeMTHnqdfpUcRVJBRJ4GQ2XHU2ruVrdJqZhLz',
ID: '212'
};
Main.js
import {
getNFT
} from 'interact.js';
// This function is executed when a user clicks on a button
let getAllocatedNFT = async () => {
try {
let response = await getNFT();
console.log('response from server:: '+response);
}catch(e){
console.log(e);
}
};
console:
response from server:: undefined
getNFT code execute // This is executed correctly after 2 seconds
You have to return promise which will resolve your webAPI(setTimeout)
Please use like below:
const getNFT = async () => {
return new Promise(resolve => setTimeout(() => {
console.log("getNFT code execute")
resolve(true)
}, 2000)
);
};

React customHook using useEffect with async

I have a customHook with using useEffect and I would like it to return a result once useEffect is done, however, it always return before my async method is done...
// customHook
const useLoadData = (startLoading, userId, hasError) => {
const [loadDone, setLoadDone] = useState(false);
const loadWebsite = async(userId) => {
await apiService.call(...);
console.log('service call is completed');
dispatch(someAction);
}
useEffect(() => {
// define async function inside useEffect
const loadData = async () => {
if (!hasError) {
await loadWebsite();
}
}
// call the above function based on flag
if (startLoading) {
await loadData();
setLoadDone(true);
} else {
setLoadDone(false);
}
}, [startLoading]);
return loadDone;
}
// main component
const mainComp = () => {
const [startLoad, setStartLoad] = useState(true);
const loadDone = useLoadData(startLoad, 1, false);
useEffect(() => {
console.log('in useEffect loadDone is: ', loadDone);
if (loadDone) {
// do something
setStartLoad(false); //avoid load twice
} else {
// do something
}
}, [startLoad, loadDone]);
useAnotherHook(loadDone); // this hook will use the result of my `useLoadData` hook as an execution flag and do something else, however, the `loadDone` always false as returning from my `useLoadData` hook
}
It seems in my useDataLoad hook, it does not wait until my async function loadData to be finished but return loadDone as false always, even that I have put await keyword to my loadData function, and setLoadDone(true) after that, it still returns false always, what would be wrong with my implementation here and how could I return the value correct through async method inside customHook?
Well...it seems to be working after I put the setLoadDone(true); inside my async method, not inside useEffect, although I am not sure why...
updated code:
// customHook
const useLoadData = (startLoading, userId, hasError) => {
const [loadDone, setLoadDone] = useState(false);
const loadWebsite = async(userId) => {
await apiService.call(...);
console.log('service call is completed');
dispatch(someAction);
setLoadDone(true);
}
useEffect(() => {
// define async function inside useEffect
const loadData = async () => {
if (!hasError) {
await loadWebsite();
}
}
// call the above function based on flag
if (startLoading) {
await loadData();
// setLoadDone(true); doesn't work here
}
}, [startLoading]);
return loadDone;
}

Inconsitant mergeMap behaviour

I am currently working on a file uploading method which requires me to limit the number of concurrent requests coming through.
I've begun by writing a prototype to how it should be handled
const items = Array.from({ length: 50 }).map((_, n) => n);
from(items)
.pipe(
mergeMap(n => {
return of(n).pipe(delay(2000));
}, 5)
)
.subscribe(n => {
console.log(n);
});
And it did work, however as soon as I swapped out the of with the actual call. It only processes one chunk, so let's say 5 out of 20 files
from(files)
.pipe(mergeMap(handleFile, 5))
.subscribe(console.log);
The handleFile function returns a call to my custom ajax implementation
import { Observable, Subscriber } from 'rxjs';
import axios from 'axios';
const { CancelToken } = axios;
class AjaxSubscriber extends Subscriber {
constructor(destination, settings) {
super(destination);
this.send(settings);
}
send(settings) {
const cancelToken = new CancelToken(cancel => {
// An executor function receives a cancel function as a parameter
this.cancel = cancel;
});
axios(Object.assign({ cancelToken }, settings))
.then(resp => this.next([null, resp.data]))
.catch(e => this.next([e, null]));
}
next(config) {
this.done = true;
const { destination } = this;
destination.next(config);
}
unsubscribe() {
if (this.cancel) {
this.cancel();
}
super.unsubscribe();
}
}
export class AjaxObservable extends Observable {
static create(settings) {
return new AjaxObservable(settings);
}
constructor(settings) {
super();
this.settings = settings;
}
_subscribe(subscriber) {
return new AjaxSubscriber(subscriber, this.settings);
}
}
So it looks something like this like
function handleFile() {
return AjaxObservable.create({
url: "https://jsonplaceholder.typicode.com/todos/1"
});
}
CodeSandbox
If I remove the concurrency parameter from the merge map function everything works fine, but it uploads all files all at once. Is there any way to fix this?
Turns out the problem was me not calling complete() method inside AjaxSubscriber, so I modified the code to:
pass(response) {
this.next(response);
this.complete();
}
And from axios call:
axios(Object.assign({ cancelToken }, settings))
.then(resp => this.pass([null, resp.data]))
.catch(e => this.pass([e, null]));

How do i prevent endless loop in while loop in action creator?

Trying to implement some kind of game loop, that will run until conditions are met.
However during testing I just can't solve the problem of while loop not waiting for resolve of promises, instead it just calls them over and over again causuing browser to crash.
The combatStart() is called when component is mounted
export const combatStart = () => {
return function (dispatch, getState) {
while (getState().mechanics.noOfEnemiesAttacked < 5) {
let setTimeoutPromise = new Promise(resolve => {
let success = true;
setTimeout(function () { resolve(success) }, 3000);
})
setTimeoutPromise.then((resp) => {
if(resp){
dispatch({
type: 'INCREMENT_ENEMIES_ATTACKED'
})
}
})
}
}
}
When i dispatch the action the "noOfEnemiesAttacked" increments, and when it reaches 5 the loop should stop. So it should last around 15 seconds.
The code works until I add the while loop, otherwise it works as expected, increments the value after 3 seconds when component is mounted.
How can I make this work?
Recursively doesnt work, it doesnt loop, just goes once:
export const combatStart = () => {
return function (dispatch, getState) {
let setTimeoutPromise = new Promise(resolve => {
let success = true;
setTimeout(function () { resolve(success) }, 2000);
})
setTimeoutPromise.then((resp) => {
if (resp) {
dispatch({
type: 'INCREMENT_ENEMIES_ATTACKED'
})
}
if (getState().mechanics.noOfEnemiesAttacked < 5) {
console.log(getState().mechanics.noOfEnemiesAttacked)
combatStart();
}
})
}
}
Wrapped it in a function, now it should work
export const combatStart = () => {
return function (dispatch, getState) {
function foo(){
let setTimeoutPromise = new Promise(resolve => {
let success = true;
setTimeout(function () { resolve(success) }, 2000);
})
setTimeoutPromise.then((resp) => {
if (resp) {
dispatch({
type: 'INCREMENT_ENEMIES_ATTACKED'
})
}
if (getState().mechanics.noOfEnemiesAttacked < 5) {
console.log(getState().mechanics.noOfEnemiesAttacked)
combatStart();
foo();
}
})
}
foo();
}
}

Angular2 Observable with interval

I have a function that needs to be called about every 500ms. The way I am looking at doing it with angular2 is using intervals and observables. I have tried this function to create the observable:
counter() {
return Observable.create(observer => {
setInterval(() => {
return this.media.getCurrentPosition();
}, 500)
})
}
With this code for the subscriber:
test() {
this.playerService.initUrl(xxxx) // This works
this.playerService.counter().subscribe(data => {
res => {
console.log(data);
}
})
}
I am very new to observables and angular2 so I might be taking the wrong approach completely. Any help is appreciated.
The Observable class has a static interval method taking milliseconds (like the setInterval method) as a parameter:
counter() {
return Observable
.interval(500)
.flatMap(() => {
return this.media.getCurrentPosition();
});
}
And in your component or wherever:
test() {
this.playerService.initUrl(xxxx) // This works
this.playerService.counter().subscribe(
data => {
console.log(data);
}
);
}

Categories