react add/edit user not working simultaneously - reactjs

We are using React 16.1.1 version along with Redux.
If already one react forms Add user process is going on , which is taking a bit longer time, application not allowing to add another user again ( if earlier process is not completed ). Save button not getting hit again.
Is it possible to have concerent ( add user events ) multiple user addition one after another even though its taking longer duration
Sample Code below
If AddUser request is taking long time, then application wont allow to add another new user immidiately if we do so.
/* Saga File ************************************/
export function* watchAddUser() {
while (true) {
const action = yield take(CREATE_USER_REQUEST)
try {
const response = yield call(userService.addUser, {
userData: action.payload.userdata
})
yield put(addUserSuccess(response))
// Call for User listing service
const responseForUserList = yield call(userService.index)
} catch (error) {
yield put(addUserFailure(error.data))
}
}
}
/* Saga File ************************************/
Is it possible to have one saga action is yet processing , still we are initiating same action again.
Ex:
If user "ABC" record is getting added via addUser form, this process is taking more than 2 minutes time. Backend java thread is running to complete the process.
Meanwhile we came on user listing page to add new record and and start another user record "xyz" creation, which is not working as first user record call saga process is not completed.
Is it possible to achieve it , like shown in above example assuming "CREATE_USER_REQUEST" process is not completed, so how to make is another user creation working ?

Found below link to overcome new async call request.
https://github.com/redux-saga/redux-saga/tree/master/docs/api#spawnfn-args
yield spawn(userList, action)
"creates a detached task. A detached task remains independent from its parent and acts like a top-level task. The parent will not wait for detached tasks to terminate before returning and all events which may affect the parent or the detached task are completely independents (error, cancellation)."
It is working now.
Thank you

Related

Avoid rate limit for changing voice channel name discord js 13

I'm trying to create a slash command using discord.js v13 to change the names of voice channels. I am using this code to do this :
module.exports = {
data: new SlashCommandBuilder()
.setName('name')
.setDescription('Set name for your voice channel')
.addStringOption(option => option.setName('name').setDescription('Enter your name').setRequired(true)),
async execute(interaction) {
const name = interaction.options.getString('name');
if (!interaction.member.voice.channel) await interaction.reply('Error not in a voice channel!');
else {
await interaction.member.voice.channel.setName(name);
await interaction.reply('Done!');
}
},
};
This code is fine and makes the job done. But as you know I can change the voice channel's name only 2 times per 10 minutes because of the limit rate. So if a user tries to change the voice channel's name for the third time, I won't get any error on the console, and discord js will queue this request for later and will do it after 10 minutes. But the user gets this error on discord: This interaction failed.
I want to check if there was a rate limit for my request, and if is, don't send the request and just reply to the user. Is this possible?
There is no inherent functionality that is able to handle the situation in the way you want it to, but the problem is soluble using regular old JavaScript. For example, you could use an integer to indicate how many times the command has been used and use setTimeout() to decrement it 10 minutes after the command was called. That way you can check if the int is equal to 2 in which case you skip the .setName().
There are undoubtedly other ways to implement the same or similar behavior, but, to answer your question, unfortunately the discordjs/voice library does not provide any simple way to do it.

Correct place to audit query in Hot Chocolate graphql

I am thinking should I audit user queries in HttpRequestInterceptor or DiagnosticEventListener for Hot Chocolate v11. The problem with latter is that if the audit failed to write to disk/db, the user will "get away" with the query.
Ideally if audit fail, no operation should proceed. Therefore in theory I should use HttpRequestInterceptor.
But How do I get IRequestContext from IRequestExecutor or IQueryRequestBuilder. I tried googling but documentation is limited.
Neither :)
The HttpRequestInterceptor is meant for enriching the GraphQL request with context data.
The DiagnosticEventListener, on the other hand, is meant for logging or other instrumentations.
If you want to write an audit log, you should instead go for a request middleware. A request middleware can be added like the following.
services
.AddGraphQLServer()
.AddQueryType<Query>()
.UseRequest(next => async context =>
{
})
.UseDefaultPipeline();
The tricky part here is to inspect the request at the right time. Instead of appending to the default pipeline, you can define your own pipeline like the following.
services
.AddGraphQLServer()
.AddQueryType<Query>()
.UseInstrumentations()
.UseExceptions()
.UseTimeout()
.UseDocumentCache()
.UseDocumentParser()
.UseDocumentValidation()
.UseRequest(next => async context =>
{
// write your audit log here and invoke next if the user is allowed to execute
if(isNotAllowed)
{
// if the user is not allowed to proceed create an error result.
context.Result = QueryResultBuilder.CreateError(
ErrorBuilder.New()
.SetMessage("Something is broken")
.SetCode("Some Error Code")
.Build())
}
else
{
await next(context);
}
})
.UseOperationCache()
.UseOperationResolver()
.UseOperationVariableCoercion()
.UseOperationExecution();
The pipeline is basically the default pipeline but adds your middleware right after the document validation. At this point, your GraphQL request is parsed and validated. This means that we know it is a valid GraphQL request that can be processed at this point. This also means that we can use the context.Document property that contains the parsed GraphQL request.
In order to serialize the document to a formatted string use context.Document.ToString(indented: true).
The good thing is that in the middleware, we are in an async context, meaning you can easily access a database and so on. In contrast to that, the DiagnosticEvents are sync and not meant to have a heavy workload.
The middleware can also be wrapped into a class instead of a delegate.
If you need more help, join us on slack.
Click on community support to join the slack channel:
https://github.com/ChilliCream/hotchocolate/issues/new/choose

Redirect the page after the account received some amount of balance in [payable] method?

When I use payable method, the page redirects to the wallet to approve the amount, but after the redirection, it returns to the old page, and the code below after the redirection is not run.
Here is the rust contract function:
#[payable]
pub fn add_liquidity(&mut self, tokens: u128, account_id: AccountId) -> u128 {
let amount = env::attached_deposit();
}
Here, the reactjs code:
onSubmit={async (values, actions) => {
try {
const data = await nearvar.contract.add_liquidity({"tokens": values.buy.toString(), "account_id": "amiyarust.testnet"}, 95000000000000, 500)
// Page redirects here. Code below is not run.
actions.setSubmitting(false)
history.push(`/hello`)
} catch (e) {
console.error(e)
}
I want to run history.push(`/hello`) after redirection.
But it refreshes the page, and the form is rendered again.
How to do solve it?
You must store something in localStorage before the redirection.
e.g. what do you expect to have happened with the account prior to redirection?
Something like their current balance and also you expect it to increase by 1 N.
Then they are redirected back to your page, you should check this condition and then continue with the rest of your code.
There is an example of this here:
https://github.com/near-examples/nearnames/blob/54dd7dd1c6adca4688c76c78db3ea6bd10ed2a13/src/state/near.js#L93-L110
Specifically this:
https://github.com/near-examples/nearnames/blob/54dd7dd1c6adca4688c76c78db3ea6bd10ed2a13/src/state/near.js#L106
Which get's read back on redirect here:
https://github.com/near-examples/nearnames/blob/54dd7dd1c6adca4688c76c78db3ea6bd10ed2a13/src/state/near.js#L55
So this app is "aware" of pending transactions (accounts that should be created) and then when the user is redirected, the app checks to see if the accounts were really created via the TX.
Then you can display these links, etc...

Restrict Previous api Request in search functioanlity

i am using react js,
have search field
<input
type="search"
onChange={this.updateSearchText}/>
function updateSearch:
updateSearchText = (e) => {
this.setState({
searchText: e.target.value
}, function () {
fetch("https://api.example.com/search/?key"+ this.state.searchText)
.then((response) => {
this.props.searchResult(response.data)
})
});
};
my issue is that if type text very quickly, first letter triggers search request and it update the props after second request has sent. so i get only first letters result.
how can i restrict first request if i type second one?
You can use "throttling" and "debouncing" your input. You can refer https://css-tricks.com/debouncing-throttling-explained-examples/ to understand it.
One of the solution that worked for me was to create "queue". The purpose of the queue was if we add a task to the queue, the task goes in front of the queue and if we add a second task to the queue, the task goes in the second position. If we add a third task to the queue, the task replaces the second.
So there is a maximum of two tasks in the queue. As soon as the first task has ended, the second task is executed etc.
So you always have the same result, and you limit your api calls in function of many parameters. If the user has a slow internet connexion, the first request will take some time to execute, so there won't be a lot of requests.

Silverlight 4 callback is accumulating with each button press

I'm writing a Silverlight 4 application using "Silverlight 4 Unleashed" as a foundation.
I have a ChildWindow for loggin in with Username, Password, and Remember Me. The OK button is tied to my AuthUserViewModel SignIn using RelayCommand.
Since I'm just starting, I don't have any data validation yet and noticed something weird.
If I click "OK" on my Login child window, my Action callback tells me I have invalid credentials in a MessageBox...which is perfect. I'm using my own Authentication service for various reasons.
However, if I click "OK" again, my service gets called once, but the Action callback is fired twice, telling me I have invalid credentials. If I press "OK" again, the service is called once, but the Action callback is fired three times, and so on and so on.
Why would it be doing that?
Here is the offending code:
public void SignIn(AuthUserDataModel authUser, Action<ErrorContainer> callback)
{
EnsureClient();
client.SignInCompleted += (sender, result) =>
callback(new ErrorContainer
{
AsyncException = result.Error,
CustomError = result.Result.CustomMessage //holds "Invalid credentials"
});
client.SignInAsync(authUser);
}
Like I said, the button event is fired once, the web service is called once, but the callback is fired an amount equaling the number of times I press OK.
Thank you.
Ah! your client object is a field, and you ensured that it is shared across calls. It prevent it from being initialized on each SignIn call, but each time you add an handler to the SignInCompleted vent before executing the SignInAsyncFunction.
Therefore it's normal that the handler gets executed one time by subsequent SignIn.
To prevent this, you have 2 approaches:
1) create a new client in each SignIn call (it will be garbage collected later)
2) attach your handler when you initialize the client.
ie in your EnsureClient, you should have something like:
if(client == null)
{
client = new MyClient();
client.SignInCompleted +=(sender,result) =>{...};
}
and in the SignIn function:
EnsureClient();
client.SignInAsync(authUser);

Resources