Adding to an existing object to make it reactive - vue.js

I have several rows of mysql data held in a vuex state, and this is the format
[{
"id": "1",
"property_country": "usa",
"property_name": "i and m towers",
"property_stars": "4",
"property_city": "austin",
"property_region": "texas",
"property_type": "serviced partment",
"date_created": "3563763673",
"date_updated": "33377363",
"the_user_id": "1"
}, {
"id": "2",
"property_country": "uk",
"property_name": "eagle towers",
"property_stars": "5",
"property_city": "kampala",
"property_region": "kampala",
"property_type": "motel",
"date_created": "3563763673",
"date_updated": "33377363",
"the_user_id": "1"
},
I am adding and getting back an object that i would like to add to the existing object
This is my mutation
CRUD_CREATE_PROPERTY: (state, response) => {
console.log(response.data);
state.properties.push(response.data)
//Vue.set(state.properties, response.data.property.id, response.data);
},
according to the docs https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects on how to make the object reactive, this is the format
Vue.set(vm.someObject, 'b', 2)
I am returning a normal mysql row with data such as this
{
"id": "3",
"property_country": "canada",
"property_name": "good motel",
"property_stars": "4",
"property_city": "montreal",
"property_region": "montreal",
"property_type": "camp",
"date_created": "3563763673",
"date_updated": "33377363",
"the_user_id": "1"
}
How can i add the new row to make it appear in my template reactively?

I ended up puttting the part i wanted to be reactive into its own component and gave it a unique key.In my case it was a table and i aptly named my component <Table />and its not even a protected keyword to my surprise
<Table :key="componentKey" />
I then created this method
forceRerender() {
this.componentKey += 1;
},
and accessed it when committing a mutation
.then( (response) => {
this.$store.commit('CRUD_CREATE_PROPERTY', response);
this.forceRerender();
})
also pay attention to the arrow function since this wouldn't work on old style javascript functions,since nowadays arrow function is now vanilla javascript.
i give credit to Michael Thiessen's article on Key-changing to force re-renders of a component which you can read here https://michaelnthiessen.com/force-re-render/

Related

pymongo: Document must be an instance of dict

Afternoon,
I'm facing a problem with pymongo, I'm not able to set up correctly the parameter to insert into MongoDB via insert_many(). I came across with de following error:
TypeError: document must be an instance of dict, bson.son.SON,
bson.raw_bson.RawBSONDocument, or a type that inherits from
collections.MutableMapping [while running 'Insere no MongoDB']
What am I doing wrong ?
class InsertMongoDB(beam.DoFn):
def process(self, element):
arqJson=json.loads(element)
client = MongoClient("mongodb://user:password#mkp-cr-marketplace-core.lcr88.gcp.mongodb.net/db-poc-base360?retryWrites=true&w=majority%20")
db = client['db-poc-base360']
db.tbPropostaSucesso.insert_many(arqJson)
# tbPropostaErro = db['tbPropostaErro']
# tbPropostaErro
resultado = 0
yield resultado
I receive a messagem from Google PubSub and forward it to a method called InsertMongoDB().
I don't know how to suit my massage, whose value is in a json format, to use it correctly in the insert_many().
When I debug my variable "arqJson" has :
The json that I'm using is :
{
"Status": "Sucesso ",
"Documento": {
"Apolice": [{
"ItemAuto": [{
"nmTipo": "FOX",
"nrItem": "000001",
"nmMarca": "VOLKSWAGEN",
"aaModelo": "2017",
"cdModelo": "0017664",
"nmModelo": "TRENDLINE 1.0 FLEX 12V 5P",
"aaFabricacao": "2016",
"nmTipoVeiculo": "Hatch"
}, {
"nmTipo": "FOX",
"nrItem": "000001",
"nmMarca": "VOLKSWAGEN",
"aaModelo": "2017",
"cdModelo": "0017664",
"nmModelo": "TRENDLINE 1.0 FLEX 12V 5P",
"aaFabricacao": "2016",
"nmTipoVeiculo": "Hatch"
}],
"ItemProp": [{
"dsUF": "MG",
"idLocal": "000001",
"dsCidade": "BELO HORIZONTE",
"dsEndereco": "RUA RUA RUA",
"dsComplemento": "CASA"
}],
"cdEmpresa": "1",
"idApolice": "501741",
"idEndosso": "000000",
"cdCarteira": "431",
"cdSucursal": "010",
"cdPatrimonio": "1",
"nrItemContrato": "2",
"dsTipoDocumento": "A",
"cdVeiculoSegurado": "1"
}],
"Cliente": [{
"cdCliente": "1",
"nmCliente": "Lucas",
"nrCpfCnpj": "4355582833",
"icRegistroAtivo": "1",
"cdAcaoInformacao": "A",
"dtAcaoInformacao": "2020-02-02",
"cdServicoAcaoInformacao": "cdServicoAcao",
"cdUsuarioAcaoInformacao": "cdUsuarioAcao"
}, {
"cdCliente": "2",
"nmCliente": "Lucas",
"nrCpfCnpj": "43331971",
"icRegistroAtivo": "1",
"cdAcaoInformacao": "A",
"dtAcaoInformacao": "2020-02-01",
"cdServicoAcaoInformacao": "cdServicoAcao2",
"cdUsuarioAcaoInformacao": "cdUsuarioAcao2"
}],
"Mensagem": [{
"cdMensagem": "1",
"dsMensagem": "Teste de mensagem"
}],
"EnderecoCobranca": [{
"dsUF": "RS",
"dsBairro": "INTEGRAÇÃO",
"dsCidade": "PAROBE",
"cdEndereco": 1,
"dsEndereco": "RUA RUA RUA",
"nrEndereco": "280",
"dsComplemento": "",
"icRegistroAtivo": "1",
"cdAcaoInformacao": "A",
"dtAcaoInformacao": "2020-02-02",
"cdServicoAcaoInformacao": "cdServicoAcao",
"cdUsuarioAcaoInformacao": "cdUsuarioAcao"
}, {
"dsUF": "SP",
"dsBairro": "INTEGRAÇÃO2",
"dsCidade": "POC2",
"cdEndereco": 2,
"dsEndereco": "RUA B",
"nrEndereco": "222",
"dsComplemento": "CASA 2",
"icRegistroAtivo": "1",
"cdAcaoInformacao": "A",
"dtAcaoInformacao": "2020-02-01",
"cdServicoAcaoInformacao": "cdServicoAcao2",
"cdUsuarioAcaoInformacao": "cdUsuarioAcao2"
}]
}
}
2020/11/20:
At the moment I'm struggling with the format of arqJson that I need to use in the insert_one(arqJson).
I forgot to mention that my method InsertMongoDB receives the arqJson from another method called InsertPostgreSQL.
InsertPostgreSQL does:
Receive the message from Pubsub;
-Transform the element : json.dumps(json.loads(element))
Save it into arqJson. After that, InsertMongoDB is called.
At this moment, I don't know how to format "element" (whose type is list) and save it into arqJson, because I have this error:
raise TypeError("%s must be an instance of dict, bson.son.SON, "
TypeError: document must be an instance of dict, bson.son.SON,
bson.raw_bson.RawBSONDocument, or a type that inherits from
collections.MutableMapping [while running 'Insere no MongoDB']
Thank you,
Juliano
The solution is :
The first error is because your JSON contains a single document not
multiple docs for an insert many. If you use brackets like this
db.tbPropostaSucesso.insert_many([arqJson]) and convert it to a list
with a single element it will work. Or you can try
insert_one(arqJson). – DaveStSomeWhere 5 hours ago
Thank you DaveStSomeWhere
I had the same problem, and what worked for me was adding retryWrites=false to the connection URL:
mongodb+srv://user:pass#server/etc...etc?retryWrites=false

Use sprintf syntax inside logstash's sprintf syntax

For the below data structure:
{
"sprints": [
{
"id": 17193,
"name": "Sprint 12"
},
{
"id": 16510,
"name": "Sprint 11"
}
],
"velocityStatEntries": {
"16510": {
"estimated": {
"value": 49
},
"completed": {
"value": 36
}
},
"17193": {
"estimated": {
"value": 52
},
"completed": {
"value": 70
}
}
}
}
Given this, I want to be able to produce an Elasticsearch object that's easier to handle, by adding the values of the Estimated and Completed fields to the sprints with their matching IDs.
Ideally, I would like to handle this without writing Ruby, but I am not finding a logstash-native solution that handles this scnenario.
First, I split the data on the sprints field using split, so, I only have a single sprints object, and can use [sprints][id] to know what sprint I'm processing.
Then, I have attempted to work with the mutate filter, in one of two ways:
- using merge to add the [velocityStateEntries][] object to the
current sprint
- using add_field to add the two fields I need
Syntactically, is this possible? Ideally, I would want to be able to do a 'double substitution' of sorts, obtaining the estimated time for the current sprint something like:
add_field => {
"estimatedTime" => "%{[velocityStatEntries][%{[sprints][id]}][estimated][value]}"
}
but this only seems to work with a hardcoded format such as "estimatedTime" => "%{[velocityStatEntries][1234][estimated][value]}"
Do I have to use the Ruby format for this?
For what it's worth, the Ruby solution is very simple:
ruby {
code => "
sprintId = event.get('[sprints][id]');
estimated = event.get('[velocityStatEntries]['+(sprintId).to_s+'][estimated][value]');
completed = event.get('[velocityStatEntries]['+(sprintId).to_s+'][completed][value]');
event.set('[sprints][estimatedUnits]', estimated);
event.set('[sprints][completedUnits]', completed);
"
}

How to add modifiers to cart line item in BigCommerce Api

I already tried the solution given in this Cart API V3: Can't create a Cart for product that has options link but it's not working for me.
modifier is extra fitting added to the product like "name tag" for suitcase.
I tried to add the modifier in "option_selections" like below but it returns 422 error.
Request:
{
"quantity":"1",
"product_id":"5846",
"variant_id":150922,
"list_price":" 170.00",
"option_selections":[{"option_id":23800, "option_value":"10088"}]
}
Response:
StatusCode: 422, ReasonPhrase: 'Unprocessable Entity'
Thanks for your reply in advance.
If you're creating a new cart, try this request body (POST to /carts endpoint):
{
"line_items": [
{
"quantity": 1,
"product_id": 76,
"list_price": 170.00,
"option_selections": [
{
"option_id": 21506,
"option_value": 10090
}
]
}
]
}
You shouldn't have quotes around any of these field values--list_price, product_id, etc all accept a number, not a string.
If you want to add a new line item to an existing cart, you can use the same request body as above. The request will be a POST to carts/{cartID}/items
EDIT:
If you are updating a line item that already exists in the cart, you'll want to make a PUT to /carts/{cartID}/items/{itemID}.
Request body:
{
"line_item": {
"quantity": 1,
"product_id": 76,
"list_price": 170.00,
"option_selections": [
{
"option_id": 21506,
"option_value": 10090
}
]
}
}
Note: it does need to be "line_item" rather than "line_items" when updating a single cart item. I'll work with our documentation team to get this updated in the API reference.
I was able to solve the issue, though I agree with Karen White's answer, I wanted to add a product which has options like colors and modifiers too. Which I was not able to achieve with that. I used the following data to add product with option and modifier.
Instead of passing variant_id, pass variant as option (option_id gets option's id and option_value gets option value's id) and pass modifier as option (modifier option_id gets option's id and option_value gets option value's id)
{
"line_items": [{
"quantity": 1,
"product_id": 5846,
"option_selections": [{
"option_id": 23799,
"option_value": 10173
}, {
"option_id": 23800,
"option_value": 10088
}]
}]
}

Figure out different values to send partial update to server

From a form submission I receive two objects: the original values and the dirty values. I like to figure out how to create a diff to send to the server using the following rules:
id field of the root object should always be included
all changed primitive values should be included
all nested changes should be included as well.
if a nested value other than id changed, it should include id as well.
Original values:
{
"id":10,
"name": "tkvw"
"locale": "nl",
"address":{
"id":2,
"street": "Somewhere",
"zipcode": "8965",
},
"subscriptions":[8,9,10],
"category":{
"id":6
},
}
Example expected diff objects:
1) User changes field name to "Foo"
{
"id":10,
"name":"foo"
}
2) User changes field street on address node and category
{
"id":10,
"address":{
"id": 2,
"street":"Changed"
},
"category":{
"id":5
}
}
I do understand the basics of functional programming, but I just need a hint in the right direction (some meta code maybe).
Take a look at JSON Patch (rfc6902), JSON Patch is a format for describing changes to a JSON document. For example:
[
{ "op": "replace", "path": "/baz", "value": "boo" },
{ "op": "add", "path": "/hello", "value": ["world"] },
{ "op": "remove", "path": "/foo"}
]
You generate a patch by comparing to JS objects/arrays, and then you can apply the patch to the original object (on the server side for example) to reflect changes.
You can create a patch using the fast-json-patch lib.
const obj1 = {"id":10,"name":"tkvw","locale":"nl","address":{"id":2,"street":"Somewhere","zipcode":"8965"},"subscriptions":[8,9,10],"category":{"id":6}};
const obj2 = {"id":10,"name":"cats","locale":"nl","address":{"id":2,"street":"Somewhere","zipcode":"8965"},"subscriptions":[8,9,10,11],"category":{"id":7}};
const delta = jsonpatch.compare(obj1, obj2);
console.log('delta:\n', delta);
const doc = jsonpatch.applyPatch(obj1, delta).newDocument;
console.log('patched obj1:\n', doc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-json-patch/2.0.6/fast-json-patch.min.js"></script>

Cannot write out the value of a key in an object, but I can console log it

I am doing some work in React Native, and currently I am going through an API to retrieve some data. I stored the data in my state and it looks like this
{
"id": "847469",
"name": "Allsvenskan",
"tournamentFK": "11075",
"gender": "male",
"countryFK": "6",
"startdate": "2017-03-31T22:00:00+00:00",
"enddate": "2017-11-05T20:00:00+00:00",
"n": "2",
"ut": "2017-06-20T13:02:07+00:00",
"country_name": "Sweden",
}
I have tried something like
return Object.keys(this.state.tournament).forEach(key => (
<Text key={key}>
{console.log(this.state.tournament[key])}
{this.state.tournament[key]}
</Text>
);
The console.log works perfectly. I can see every value of every key.
But, I cannot print it out. I can't see anything on my phone. It's nothing about the color either, because I can see other text.
Any clues?