Axios Post inside loop with changing variable REACT - javascript

I have an array of labels for form inputs named changing_variable, which are dependent on what a user selects from a drop down menu, so these are unknown.
I need to be able to let the property of the Axios.post method, equal to the variable in order to input the correct data into my database.
Any examples I see online have properties like:
name: this.name
age: this.age
However this cannot work for me since I cannot hard code the values since they change depending on the user input, and also there is over a hundred for each user input.
If anyone can help me pass this changing variable to my backend. Thanks
My current code :
var i;
var changing_variable;
for(i=1; i<arr.length; i++)
{
changing_variable = inputValues[i].text
Axios.post(URL, changing_variable)
.then(res => {
console.log(res);
console.log(res.data);
console.log(changing_variable)
})
}
};
EDIT
Node.js code
app.post('/create', (req,res) => {
const test_variable= req.body.changing_variable;
db.query("INSERT INTO iptable (test_variable) VALUES(?)",
[test_variable], (err,result) =>{
if(err){
console.log(err)
}else {
res.send("Values Inserted")
}
}
)
});
Terminal error message
code: 'ER_BAD_NULL_ERROR',
errno: 1048,
sqlMessage: "Column 'test_variable' cannot be null",
sqlState: '23000',
index: 0,
sql: 'INSERT INTO iptable (test_variable) VALUES(NULL)'

The solution is Using application/x-www-form-urlencoded, URLSearchParams
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use the URLSearchParams API.
const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);
REF https://github.com/axios/axios#urlsearchparams

Related

RTK MySql: how to split variable array into seperate entries

I have
const {data, error, isLoading } = useFetchBulkClassesQuery(something)
to pass data to MySql via this API:
fetchBulkCclasses: builder.query ({
query: (something) => {
return {
url: '/bulkclasses',
params: {
class: something
},
method: 'GET'
at the backend, I have
tyapp.get("/bulkclasses", (req, res) => {
const q = 'select * from recent where ticker in (?)'
db.query(q, [[req.query.ticker]], (err, data) => {
if(err) {return res.json(err)}
return res.json(data)pe here
it al works fine if I use a single variable, like something = 'ClassA'
But I want to use it for multiple entries like ClassA, ClassB, ClassC, ...
But it only takes the first one (or the last one depending on what I try).
What am I doing wrong? Or what haven't I tried (or what do I not know)?
I tries:
Something = ['ClassA', 'ClassB', ...] -> the thing that get passed to the backend is 'ClassA, ClassB' en and it needs to be 'ClassA', 'ClassB', ...
Something = [[ClassA], [ClassB],...] -> same result
It seemed a bit impossible to do, so I did choose the easiest solution: changing the design of my tables and update the query.

HubspotClient - Update contact by email id is not working

In NodeJS, I'm using "#hubspot/api-client": "^7.1.2".
Created hubspot client using accessToken as follows
const hubSpotClient = new hubspot.Client({ accessToken });
When I try to update the contact using email it's throwing error
Request:
const idProperty = 'email';
const response = await hubSpotClient(store).crm.contacts.basicApi.update(email, idProperty, contact);
Response:
ERROR {
"statusCode": 404,
"body": {
"status": "error",
"message": "Object not found. objectId are usually numeric.",
"correlationId": "71e911d3...",
"context": {
"id": [
"testemail#..."
]
},
"category": "OBJECT_NOT_FOUND"
}
Create contact is working fine with this client but updating by email is not working.
Anything out of place or syntax error in passing the idProperty?
The problem is in your implementation, because it seems like you are not using properly the Hubspot API.
If you check the function signature of the basicApi.update
public async update(contactId: string, simplePublicObjectInput: SimplePublicObjectInput, idProperty?: string, _options?: Configuration): Promise<RequestContext> {
Basically, you need to pass down a contactId, and then a simplePublicObjectInput that is basically an object that represents your update.
Your code should look like this:
import { Client } from "#hubspot/api-client";
const hubspotClient = new Client({ accessToken: YOUR_ACCESS_TOKEN });
const contactID = 1234;
const response = await hubspotClient.crm.contacts.basicApi.update(contactID, {
properties: { email: 'my-new-email#gmail.com' },
})
Keep in mind that Hubspot always tries to follow their same guidelines as their endpoints. If your check the endpoint specification you will see the following:
Think about the Hubspot node client as just an abstraction of some http client, but at the end does exactly the same as the endpoints described in their implementations.
For that reason, in your implementation, Hubspot is returning an appropriated error, since you are not giving the contactId in the first argument, Hubspot is telling you: "Object not found. objectId are usually numeric." Because indeed a Contact ID is numeric and you are using the value of an email --string-- instead.
If you want to "update by email"
I think that there is no direct way to do it, you might need to do a previous search of the contact by email.
You could use the searchApi.
And after getting the id just run the update.
const searchResponse = await hubspotClient.crm.contacts.searchApi.doSearch({
filterGroups: [
{
filters: [
{
value: 'email-to-search#gmail.com',
propertyName: 'email',
operator: 'EQ',
},
],
},
],
sorts: [],
properties: [],
limit: 1,
after: 0,
});
// Off course you need to improve a lot the error handling here and so on.
// This is just an example
const [contactID] = searchResponse.results;
const contactUpdateResponse = await hubspotClient.crm.contacts.basicApi.update(contactID, {
properties: { email: 'my-new-email#gmail.com' },
})
I hope this helps you!
You CAN use email as the idProperty for the hubspot/api-client get contact function, but it only works if you fill in all the other query fields before idProperty, even if they are undefined.
Here is my example of a getContactByEmail as a Google Cloud Function in Node, using the api-client, and it works great!
exports.getContactByEmail = functions.https.onCall(async (data, context) => {
const email = data.email;
const contactId = email;
const properties = ["firstname", "lastname", "company"];
const propertiesWithHistory = undefined;
const associations = undefined;
const archived = false;
const idProperty = "email";
try {
const apiResponse = await hubspotClient.crm.contacts.basicApi.getById(
contactId,
properties,
propertiesWithHistory,
associations,
archived,
idProperty
);
console.log(JSON.stringify(apiResponse.body, null, 2));
return apiResponse.properties;
} catch (error) {
error.message === "HTTP request failed"
? console.error(JSON.stringify(error.response, null, 2))
: console.error(error);
return error;
}
});

How to insert data into mysql using angular and nodejs - getting (NULL, NULL) upon insert - Problem solved

Good day,
I've been trying to learn a bit of angular and nodejs. I found a tutorial on a realtime chat app and made some few adjustment to some function of the code. But the one aspect that I cannot seem to get right is the ability for the user to post to a feed. The login process works, the user is already logged in but the user can't post. I would also like to be able to get all they data i insert from all the user to show up like a normal feedview will. Please assist.
Here are my files:
FROM MY CONTROLLER HERE IS THE CODE WHEN THE BUTTON IS PRESSED
$scope.postDatatoDd = () => {
appService.httpCall({
url: '/posts',
params: {
'posts': $scope.data.info,
'from_user_id': $scope.data.username
}
})
.then((response) => {
// $scope.$apply();
})
.catch((error) => {
alert(error.message);
});
}
and here is my route file:
this.app.post('/posts', async(request,response) => {
const reqResponse = {}
const data = {
posts : request.body.postDatatoDd,
from_user_id: request.body.username
};
if (data.posts === ''){
reqResponse.error = true;
reqResponse.message = `error, input`;
response.status(412).json(reqResponse);
} else {
const result = await helper.insertFeed(data);
if (result === null) {
reqResponse.error = true;
reqResponse.message = `they was an error.`;
response.status(417).json(reqResponse);
} else {
reqResponse.error = false;
reqResponse.userId = result.insertId;
reqResponse.message = `posted succesfully`;
response.status(200).json(reqResponse);
}
}});
and in my helper file there is this function to insert data:
async insertFeed(params){
try {
return await this.db.query(
`INSERT INTO posts (from_user_id,posts) values (?,?)`,
[params.from_user_id,params.postDatatoDd]
);
} catch (error) {
console.warn(error);
return null;
}
}
On the client side here is the button with :
<label for="postDatatoDd">Post</label>
<input type="text" id="postDatatoDd"
ng-model="data.postDatatoDd"
class="feed form-control"
placeholder="post your data here?"
/>
<button ng-click="postDatatoDd()" class="btn btn-primary">Post</button>
</div>
--- EDIT 1---
Data is being inserted now, but it is receiving the values as (NULL, NULL).
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
Other than a lot of typos when it comes to the variables reference. The code seem to be fine.
Assuming that you using appservice class somewhere in your code and its functioned, then everything else will work.
You are getting the (NULL, NULL) because you are parsing parameters that are not being properly parsed out to your helper file, please close attention to that.
appService
.httpCall({
url: "/posts",
params: {
posts: $scope.data.postbuzz,
from_user_id: $scope.data.username,
},
})
.then((response) => {
$scope.$apply();
})
.catch((error) => {
alert(error.message);
});
make sure that the data that you calling from this above function is similar to $scope parameter you passing in your route file that your requesting:
const data = {
posts : request.body.posts,
from_user_id: request.body.from_user_id}
and in your database helper class you running:
`INSERT INTO posts (from_user_id,post) values (?,?)`,
[params.from_user_id,params.posts]
Hope this was helpful
You seem to have an understand already. your question may help a lot more people in the future.
params should be as following, since the data object has properties from_user_id and posts
`INSERT INTO posts (from_user_id,posts) values (?, ?)`,
[params.from_user_id,params.posts]
Might be useful https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
If you are new to Angular you can use the code as reference.

Feathers-mongoose : Get by custom attribute in feathers-mongoose

I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.

Can't create a LookUpField

I am creating a new list and trying to add a LookUp field on the list.
I retrieve the list I want to look up against:
let list = sp.web.lists.getByTitle("Trucks");
list.get().then(list => {
this._ensureMyList("MySPListTest", list)
});
I then create the new list and the new field:
private _ensureMyList(listName: string, truckList): void {
sp.web.lists.ensure(listName)
.then((ler: ListEnsureResult) => {
if (ler.created) {
console.log("list was created");
ler.list.fields.add("LookupTest", "SP.FieldLookup", {
Group: "~Example",
FieldTypeKind: 7,
Filterable: true,
Hidden: false,
EnforceUniqueValues: true,
})
.then((result) => {
console.log("result: ", result);
});
}
});
}
I get the error:
Uncaught (in promise) Error: Error making HttpClient request in queryable: [500] ::> {"responseBody":{"odata.error":{"code":"-2146232832, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"Please use addfield to add a lookup field instead."}}},"responseHeaders":{}}
I got the Field name and TypeKind from:
https://msdn.microsoft.com/en-us/library/office/dn600182.aspx#bk_FieldLookup
I also tried using the addLookup method:
ler.list.fields.addLookup("LookupTest", truckList.Id, "Truck")
.then((result) => {
console.log("result: ", result);
});
With error:
Uncaught (in promise) Error: Error making HttpClient request in queryable: [400] ::> {"responseBody":{"odata.error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The parameter __metadata does not exist in method AddField."}}},"responseHeaders":{}}
You could consider the following options to add lookup field:
1) via Fields.addLookup method:
let list = await sp.web.lists.getByTitle(listTitle); //get list resource
let lookupList = await sp.web.lists.getByTitle(lookupListTitle).select("Id").get(); //select Lookup List Id
let field = await list.fields.addLookup(lookupFieldName, lookupList.Id ,"Title"); // add lookup field to list
2) via Fields.createFieldAsXml method:
let list = await sp.web.lists.getByTitle(listTitle); //get target list resource
let lookupList = await sp.web.lists.getByTitle("Categories").select("Id").get(); //determine lookup list id
let fieldXml = `<Field Name="Category" Type="Lookup" DisplayName="Category" List="{${lookupList.Id}}" ShowField="Title"/>`; //construct lookup field schema
let field = await list.fields.createFieldAsXml(fieldXml); //add field to list
References
PnPjs Add Fields
Update
Regarding the error which occurs while invoking Fields.addLookup method:
the parameter __metadata does not exist in method AddField.
it seems there is a bug with in the latest version (v1.2.1) for Fields.addLookup method. The point is it generates invalid payload, something like this:
{
"__metadata":{
"type":"SP.FieldCreationInformation"
},
"parameters": {
"FieldTypeKind":7,
"LookupFieldName":"Title",
"LookupListId":"{list-id}",
"Title":"Cat"
}
}
parameters should be the root tag in payload for http://<site url>/_api/web/lists(guid'<list id>')/fields('<field id>')/addfield endpoint (source)
According to the history this bug has been introduced with one of the later commit, anyway it's better to report an issue.

Categories