Object won't append to field array with react-hook-form - javascript

I'm trying to set up a form with react-hook-form (which is amazing by the way) to input a TV series where the series has an arbitrary number of seasons and each season has an arbitrary number of episodes. I know I need to have seasons as a field array, but since it doesn't seem possible to create a new field array for each season, I've created a separate episodes field array which will hold an array of objects including a "season" key so I can identify and filter which episodes belong to which season. It's possible theres a better way to set this up altogether and that might be the real problem here.
With what I have set up though, I'm running into an issue where I need to keep values in the react-hook-form hook that won't be shown on the page as part of the form like the index of the episode (so I can update it in the field array without mapping through all episodes) and the season number it belongs to. When I try to append an episode to the episodes field array though, it doesn't update properly and episodes is undefined after the first episode is appended or only keeps the value of registered fields after any subsequent appends. Definitely seems to me that this has something to do with fields in episodes not being registered as part of the form, but in my case not all fields can be part of the form. Wondering if anyone has an idea for how to work with this problem or get around out, maybe with using actual react state while keeping renders at a minimum.
Code sandbox here
https://codesandbox.io/s/determined-browser-7ppf1
Expected behavior of above: after adding a season, add multiple episodes and see "episode number" move up incrementally in the UI and see all episode information in the console after submit.
EDIT:
I'm porting over code from React where the state was like
seriesState = {
seriesTitle: "New TV Series"
seasons: [
{
seasonTitle: "Season 1",
seasonNumber: 1,
episodes: [
{
episodeNumber: 1,
title: "Season 1 Episode 1"
},
{
episodeNumber: 2
title: "Season 1 Episode 2"
}
]
},
{
seasonTitle: "Season 2",
seasonNumber: 2,
episodes: [
{
episodeNumber: 1,
title: "Season 2 Episode 1"
},
{
episodeNumber: 2,
title: "Season 2 Episode 2"
}
]
}
]
}
and trying to rewrite it for react-hook-form by rewriting it like below
seriesState = {
seriesTitle: "New TV Series"
seasons: [
{
number: 1,
seasonTitle: "Season 1"
},
{
number: 2,
seasonTitle: "Season 2"
}
],
episodes: [
{
seasonNumber: 1,
episodeNumber: 1
episodeTitle: "season 1 episode 1"
},
{
seasonNumber: 1,
episodeNumber: 2
episodeTitle: "season 1 episode 2"
},
{
seasonNumber: 2,
episodeNumber: 1
episodeTitle: "season 2 episode 1"
},
{
seasonNumber: 2,
episodeNumber: 2
episodeTitle: "season 2 episode 2"
}
]
}
and now I'm changing it to

Related

Objection insertGraph, insert new and relate or relate to existing rows

So, I'm not super knowledge with MySQL relations, upserting and such. I'm looking for an explanation on how (if?) this is possible to do.
[
{
scheduledAt: '17:55',
league: { name: 'Champions League - Group Stage' }
},
{
scheduled_at: '19:45',
league: { name: 'Champions League - Group Stage' }
},
{
scheduled_at: '19:30',
league: { name: 'Primera B Metropolitana' },
},
{
scheduled_at: '21:00',
league: { name: 'Primera B Metropolitana' }
}
]
Say I wanted to insert this graph of data. The root objects are going into the fixtures table, and the league property is this relation in the Fixtures model.
{
league: {
relation: Model.BelongsToOneRelation,
modelClass: `${__dirname}/League`,
join: {
from: 'fixtures.league_id',
to: 'leagues.id'
}
}
}
So, currently if I use insertGraph to insert all this data. It's inserts into both the fixtures and leagues table and relates as you would expect.
{
"scheduled_at": "17:55",
"league": {
"name": "Champions League - Group Stage",
"created_at": "2018-10-03T13:02:03.995Z",
"id": 1
},
"league_id": 1
"created_at": "2018-10-03T13:02:04.042Z",
"id": 1
}
However if I insert the exact same league object, it will just create another duplicate league and fixture row with the next incremented ID (2 in this case).
Is it possible for it to find if a league exists with that name, and then use that row/ID as the league_id, like so:
{
"scheduled_at": "17.55",
"league_id": 1
"created_at": "2018-10-03T13:02:04.042Z",
"id": 2
}
Sorry if I've explained this horrendously. But I'm not so hot on the terminology so I don't know what I'm actually looking to do. I feel like this is a super easy thing, but maybe my structure or method is wrong.

AngularJS - Move Object from Controller 1 to Controller 2

I'm currently learning AngularJS but I wasn't able to find a solution for this problem even though it seems trivial.
I have two lists / controllers that are getting created by factory service.
I want to remove an object from list 1 and add to list 2. When I display the object in the console after passing it, I can see it but it doesn't appear in my second list.
I have the code on GitHub - As you can see this is an assignment from coursera.
https://github.com/alaimoclaudia/assignment2_solution
I am not sure I am answering your question, but I have created a plunker based on your github code:
https://plnkr.co/edit/oNvezy5IQ9EBKMpwWq7j?p=preview
I see only one list of items in the code:
[{
name: "Milk",
quantity: "10"
}, {
name: "Donuts",
quantity: "10"
}, {
name: "Cookies",
quantity: "10"
}, {
name: "Chocolate",
quantity: "10"
}, {
name: "Apples",
quantity: "10"
}];
And it seems like the ui behaves as expected.

$lookup search Mongodb

Objective
To have an efficient search using references in MongoDB.
Background
I have a Smoothie DB on Mongo. A smoothie is an object with a reference to a Food object and it is represented like:
{
name: "Red Velvet Cake",
ingredients: [{
food_id: "strawberry_raw",
//other really cool fields
},
//other ingredients
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
}
Now, a Food object is represented by the following example:
{
"_id": "strawberry_raw",
"name": "strawberries",
//other really cool fields
}
Problem
With these schemas in mind, I am making sure that a Smoothie object knows all the Food objects that build it. Since each Smoothie object will have at most 6 or 7 food objects, I believe this is the best choice as it follows the MongoDB's Principle of least Cardinality.
However, now I want to allow the following functionalities:
Given a list of ingredient names, return all smoothies that contain at least one of those ingredients
Given a list of ingredient names, return only the smoothies that contain all those ingredients.
And I have no idea how to do it with MongdoDB.
Example
The following examples illustrate what I want.
Imagine I have the following Foods:
let foods = [{
"_id": "strawberry_raw",
"name": "strawberries"
}, {
"_id": "honeydew_melon_raw",
"name": "honeydew melon"
}, {
"_id": "coconut_milk",
"name": "homemade coconut milk"
}];
And the following Smoothies:
let smoothies = [
{
name: "Coco Berry",
ingredients: [
{ food_id: "strawberry_raw" },
{ food_id: "coconut_milk"}
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
},
{
name: "Tropical Melon",
ingredients: [
{ food_id: "honeydew_melon_raw"},
{ food_id: "coconut_milk"}
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 51"
}];
Given a search with the term "coconuts, strawberry", the functionalities would return:
Coco Berry and Tropical Melon, as both smoothie have at least one of the ingredients (coconut milk)
Coco Berry, as this smoothie has both ingredients, and the second one is missing one ingredient.
What I tried and what i need
I know that to turn a search like "coconuts" return a Food with name "Coconut Milk" I have to index the names in the Food collection, which I did.
I also searched and I found that I will likely need to use $lookup, however, I don't know how to move from that point forward. How do I do it ?
I think there is no need of adding a join or index you can use $regex,let me try my hand,consider smothie as your collection
`
db.collection.find({ingredients : {$elemMatch : {$or :[
{food_id : {$regex : "coconuts")},{food_id : {$regex : "strawberry")}]}}})
`
Your second query
`
db.collection.find({ingredients : {$elemMatch : {$and :[
{food_id : {$regex : "coconuts")},{food_id : {$regex : "strawberry")}]}}})
`

Filtering data based on dynamic check box Categories in Angular JS?

I'm trying to achieve a filter check box option with dynamic data by category and sub category.
How I want is,
[] Category
[] Sub Category
[] Sub Category
[] Category
[] Sub Category
[] Sub Category
[] Sub Category
... and so on
Assume [] as check box above.
Here's the sample json data :
[
{
"category": {
"name": "AAA - 1"
},
"parentcategory": {
"name": "AAA"
},
"title" : "XXXXX",
},
{
"category": {
"name": "AAA - 2"
},
"parentcategory": {
"name": "AAA"
},
"title" : "YYYY",
}
]
Based upon the above data, what i'm really trying to want is,
Sidebar :
[] AAA
[] AAA - 1
[] AAA - 2
Main Content :
Initially show title. After something is checked, show title which are related to that category/sub category.
Note : Pl don't think that I'm asking without any effort. I've seen some examples like in JSBin, but i couldn't find something like i wanted to achieve. Btw I'm new to Angular.
If i understand correctly you want something like that:
http://jsfiddle.net/ms403Ly8/67/
Firstly i found first parent item from your json array. Then found this parent's children and add into it.
angular.forEach($scope.itemList, function(itm) {
var filteredItem = $filter('filter')($scope.itemList, { parentcategory: itm.parentcategory.name});
if($filter('filter')($scope.parentItems, { name: itm.parentcategory.name}).length == 0){
$scope.parentItems.push({name: itm.parentcategory.name, children:filteredItem});
}
});

Ember Data does not allow duplicate entries in hasMany relationships

I have the following model:
#order/model.coffee
Order = DS.Model.extend {
line_items: DS.hasMany 'product', {async: true}
}
At some point I want to add the some products to the order. I found that I can only add the product once, adding the same product again does not work:
#product/route.coffee
...
actions:
# Not actually my code but illustrates the problem
addToCart: (product1, product2)->
order = #modelFor 'order'
console.log order.get('line_items.length') # prints 0
order.get('line_items').pushObject product1
console.log order.get('line_items.length') # prints 1
order.get('line_items').pushObject product2
console.log order.get('line_items.length') # prints 2
order.get('line_items').pushObject product1
console.log order.get('line_items.length') # prints 2
order.get('line_items').pushObject product2
console.log order.get('line_items.length') # prints 2
...
The problem is that the user might want a single item more than once. The simplest way to represent that is to have an array with duplicate entries. It seems Ember is not letting me do that for relationships. How can I add a model more than once to a relationship ?
It sounds like you actually need a line_items model with a quantity field. Just shoving more of the same item in your orders model isn't really a normalized solution.
I would recommend the following:
lineItem = DS.Model.extend({
orders: DS.belongsTo('orders'),
product: DS.belongsTo('products'),
quantity: DS.attr('number'),
});
orders = DS.Model.extend({
lineItems: DS.hasMany('lineItem', {async: true}),
customerId: DS.belongsTo('customers'),
});
products = DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
cost: DS.attr('string'),
});
This would allow you to create multiple records in your lineItem model, that will have a unique ID but be bound to a specific order, (which would solve the issue of multiple orders having the same lineItem) for example, you could have:
{
"lineItem" :
[
{
"id": 1,
"orderId": 1,
"product": 1,
"quantity": 100,
},
{
"id": 2,
"orderId": 1,
"product": 2,
"quantity": 10,
},
{
"id": 3,
"orderId": 2,
"product": 1,
"quantity": 100,
}
]
}
In this design you would remove the reference to lineItems from your json, as ember-data looks after the inverse relationship for you (if you aren't sideloading the relationship you will need to add async to your model). This will mean that if you need to change a line item, it will only affect one order, and if you need to change the order that a lineItem is related to you just do this on the lineItem model.
{
"Orders" :
[
{
"id": 1,
"customerId": 123456,
},
{
"id": 2,
"customerId": 123456,
}
]
}
They should have an id property, then they will be able to co-exist in the same array and be distinct items of the same product type - with the same name (all the same properties other than id).
Either that, or you have one record that represents a product type, and then have a quantity attribute to specify how many of each product there are..

Categories