Normalizr with Redux with nested array of objects - redux

I'm just getting started with using normalizr with Redux, and I can't make it work. Even though I can do it with plain JavaScript.
I have an array of objects
const data = [
{
data_detail: [
{
category: 'newCategory',
_id: '123',
},
],
_id: 'abc_id',
customer: {
_id: '456',
email: 'hello#gmail.com',
name: 'Bob',
},
date: '2021-01-10T01:51:24.387Z',
},
];
And I need to transform it to
const normalizedResponse = {
customers: {
'456': {
_id: '456',
email: 'hello#gmail.com',
name: 'Bob',
},
},
details: {
'123': {
category: 'newCategory',
_id: '123',
},
},
orders: {
'abc_id: {
order_detail: [123],
_id: 'abc_id',
customer: '456',
date: '2021-01-10T01:51:24.387Z',
},
},
};
Step 1: Display just orders
What I do:
const userSchema = new schema.Entity(
'orders',
);
const userListSchema = new schema.Array(userSchema);
const normalizedData = normalize(data, userListSchema);
What I get
{
"entities": {
"orders": {
"abc_id": {
"data_detail": [
{
"category": "newCategory",
"id": "123"
}
],
"id": "abc_id",
"customer": {
"id": "456",
"email": "hello#gmail.com",
"name": "Bob"
},
"date": "2021-01-10T01:51:24.387Z"
},
"abc_id-02": {
"data_detail": [
{
"category": "newCategory1",
"id": "123-02"
}
],
"id": "abc_id-02",
"customer": {
"id": "456-02",
"email": "hello#gmail.com",
"name": "Bob"
},
"date": "2001-01-10T01:51:24.387Z"
}
}
},
"result": [
"abc_id",
"abc_id-02"
]
}
What I'm trying to get:
orders: {
'abc_id: {
order_detail: [123],
_id: 'abc_id',
customer: '456',
date: '2021-01-10T01:51:24.387Z',
},
},
The question: How to remove some fields from orders and add new ones?

You have 3 different entity types in your data object. First draft out a schema for each of them:
const detail = new schema.Entity('details');
const customer = new schema.Entity('customers');
const order = new schema.Entity('orders');
Then go back and fill in the relationships. It looks like order is the outermost entity. An order contains an array of details/categories and a single customer.
const order = new schema.Entity('orders', {
data_detail: [detail],
customer,
});
All of your entities use _id instead of id, so you need to set the idAttribute.
Your data is an array of order. You can use new schema.Array(order) but you can also just use [order].
Here's your final code:
const customer = new schema.Entity("customers", {}, { idAttribute: "_id" });
const detail = new schema.Entity("details", {}, { idAttribute: "_id" });
const order = new schema.Entity(
"orders",
{
data_detail: [detail],
customer
},
{ idAttribute: "_id" }
);
const normalizedData = normalize(data, [order]);
That gives you:
{
"entities": {
"details": {
"123": {
"category": "newCategory",
"_id": "123"
}
},
"customers": {
"456": {
"_id": "456",
"email": "hello#gmail.com",
"name": "Bob"
}
},
"orders": {
"abc_id": {
"data_detail": ["123"],
"_id": "abc_id",
"customer": "456",
"date": "2021-01-10T01:51:24.387Z"
}
}
},
"result": ["abc_id"]
}

Related

How should I convert a firestore object into something I can use in expo/react-native?

This is the function I'm using to get all listings from my firestore instance. I would like to be able to retrieve the listings and add them to my listings page.
`function getListings() {
db.collection('listings').get().then((snapshot)=> {
snapshot.docs.forEach(doc => {
const id = doc.id
const data = doc.data()
console.log({id,data})
})})`
This is what logs into the console. 2 separate listings. Both objects.
`Object {
"data": Object {
"amount": Object {
"amount": "1000 ",
},
"category": Object {
"category": Object {
"backgroundColor": "purple",
"label": "Fruits",
"value": 1,
},
},
"dateToday": Object {
"dateToday": "Todays Date",
},
"description": Object {
"description": "Crystal Clear",
},
"imageUris": Object {},
"title": Object {
"title": "Spring Water",
},
"userId": Object {
"userId": "User Name",
},
},
"id": "CB59J7NL7IXgKsUU6IyS",
}
Object {
"data": Object {
"amount": Object {
"amount": "99",
},
"category": Object {
"category": Object {
"backgroundColor": "purple",
"label": "Fruits",
"value": 1,
},
},
"dateToday": Object {
"dateToday": "Todays Date",
},
"description": Object {
"description": "Granny Smith",
},
"imageUris": Object {},
"title": Object {
"title": "Apples",
},
"userId": Object {
"userId": "User Name",
},
},
"id": "Tr2GjKES85HaSdeEOZwa",
}`
How can I convert the object into data that I can use? Thanks in advance!
You first should create a class. I called MyModel.
class MyModel {
id="";
data = "";
category = "";
dateToday = "";
description ="";
imageUris ="";
userId ="";
constructor(props) {
this.data = props && props.data || this.data;
this.category = props && props.category || this.category;
this.dateToday = props && props.dateToday || this.dateToday;
this.description = props && props.description || this.description;
this.imageUris = props && props.imageUris || this.imageUris;
this.userId = props && props.userId || this.userId;
}
}
after that update the function getListings() like below.
function getListings() {
db.collection('listings').get().then((snapshot) => {
const myObjects = snapshot.docs.map((doc) => new MyModel({ ...doc.data(), id: doc.id }))
})
}

Updating a table in DynamoDb using FilterExpression

So I have this JSON object
{
"id": "c66c588e",
"players": {
"M2cfydGooAMCLpQ=": {},
"ygjjgy7678": {}
}
}
For a given player Id, I want to update that particular object, so it becomes
{
"id": "c66c588e",
"players": {
"M2cfydGooAMCLpQ=": {
"cards": [
{
"cardId": "id1",
"cardTitle": "title here"
}
]
},
"ygjjgy7678": {}
}
}
This is the query I have
const params = {
TableName: process.env.DYNAMODB_GAMES_TABLE,
Key: {
id: gameId
},
UpdateExpression: 'set players.#player = list_append(if_not_exists(#cards, :empty_list), :card)',
ExpressionAttributeNames: {
'#cards': 'cards',
'#player': playerId
},
ExpressionAttributeValues: {
':card': [{
"cardId": cardId,
"cardTitle": cardTitle,
"pun": pun
}],
':empty_list': []
},
ReturnValues: "ALL_NEW"
};
But I get this error
{
"message": "The document path provided in the update expression is invalid for update",
"code": "ValidationException",
"time": "2020-05-21T00:50:32.236Z",
"requestId": "HLJJA2QQ2POAQEAJUD3143T6PJVV4KQNSO5AEMVJF66Q9ASUAAJG",
"statusCode": 400,
"retryable": false,
"retryDelay": 38.70011614235671
}
I cannot seem to figure out how to update a particular player.
I think creating a new Index will result in additional AWS costs which I want to avoid.
I figured it out.
The key should be a valid key which you can access by obj.key and not obj[key]
Then this query will work
const params = {
TableName: process.env.DYNAMODB_GAMES_TABLE,
Key: {
id: gameId
},
UpdateExpression: 'set players.#player = list_append(if_not_exists(#cards, :empty_list), :card)',
ExpressionAttributeNames: {
'#cards': 'cards',
'#player': playerId
},
ExpressionAttributeValues: {
':card': [{
"cardId": cardId,
"cardTitle": cardTitle,
"pun": pun
}],
':empty_list': []
},
ReturnValues: "ALL_NEW"
};

Decoding Nested JSON Elements (SwiftUI)

I am trying to parse the JSON data below into the structs that are shown. I am having a helluva time trying to figure out how to get at the "nested" elements, such as elements "title:", "content:", and "excerpt:". Whenever the code runs, it barfs while parsing the nested elements.
I've looked at the Apple Developer stuff and reviewed the Playground here: https://developer.apple.com/documentation/foundation/archives_and_serialization/using_json_with_custom_types
I also tried using quicktype.io to create the data models from the sample JSON, however, in the header of the exported file from quicktype it has the line: "let blogItem = try? newJSONDecoder().decode(BlogItem.self, from: jsonData)", however, I get a compile error that jsonData is not recognized and I'm not able to find any reference to it.
struct BlogSection: Codable, Identifiable {
var id: Int
var slug: String
var link: String
var title: [BlogTitle]
var content: [ContentData]
}
struct BlogTitle: Codable, Equatable, Identifiable {
var id: UUID
var rendered: String
}
struct ContentData: Codable, Identifiable{
var id: UUID
var rendered: String
}
/**************** JSON Data ***************/
[
{
"id": 10960,
"date": "2019-10-02T01:00:07",
"date_gmt": "2019-10-02T05:00:07",
"guid": {
"rendered": "example.com/blog-template-copy-copy/"
},
"modified": "2019-09-20T07:08:41",
"modified_gmt": "2019-09-20T11:08:41",
"slug": "relationships-matter",
"status": "publish",
"type": "post",
"link": "example.com/relationships-matter/",
"title": {
"rendered": "Relationships Matter"
},
"content": {
"rendered": "<h1>Page content</h1>",
"protected": false
},
"excerpt": {
"rendered": "<p>By: Joe Schmoe<br />\nFirst Author",
"protected": false
},
"author": 57,
"featured_media": 10958,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"template": "",
"format": "standard",
"meta": [],
"categories": [
613
],
"tags": [],
"_links": {
"self": [
{
"href": "example.com/wp-json/wp/v2/posts/10960"
}
],
"collection": [
{
"href": "example.com/wp-json/wp/v2/posts"
}
],
"about": [
{
"href": "example.com/wp-json/wp/v2/types/post"
}
],
"author": [
{
"embeddable": true,
"href": "example.com/wp-json/wp/v2/users/57"
}
],
"replies": [
{
"embeddable": true,
"href": "example.com/wp-json/wp/v2/comments?post=10960"
}
],
"version-history": [
{
"count": 5,
"href": "example.com/wp-json/wp/v2/posts/10960/revisions"
}
],
"predecessor-version": [
{
"id": 10971,
"href": "example.com/wp-json/wp/v2/posts/10960/revisions/10971"
}
],
"wp:featuredmedia": [
{
"embeddable": true,
"href": "example.com/wp-json/wp/v2/media/10958"
}
],
"wp:attachment": [
{
"href": "example.com/wp-json/wp/v2/media?parent=10960"
}
],
"wp:term": [
{
"taxonomy": "category",
"embeddable": true,
"href": "example.com/wp-json/wp/v2/categories?post=10960"
},
{
"taxonomy": "post_tag",
"embeddable": true,
"href": "example.com/wp-json/wp/v2/tags?post=10960"
}
],
"curies": [
{
"name": "wp",
"href": "https://api.w.org/{rel}",
"templated": true
}
]
}
}
]
'
In the JSON you do not have arrays for title and content, so just remove the brackets
struct BlogSection: Codable, Identifiable {
var id: Int
var slug: String
var link: String
var title: BlogTitle
var content: ContentData
}
struct BlogTitle: Codable, Equatable, Identifiable {
var id: UUID
var rendered: String
}
struct ContentData: Codable, Identifiable{
var id: UUID
var rendered: String
}
Title and Content are not Arrays in the json provided so should be declared as entities. Your BlogTitle and ContentData are declared as Identifiable and have a variable for id, but both do not have an id in the json provided, so you will get a decoding error because of that as well.
The error you are getting points to a completely different problem though. How is your jsonData declared?

how to solve this in javascript?

> Locate the `displayBirthdate` function you initially defined, which took no parameter. Modify it to use object de-structuring to get just the 'dob' property of the parameter object it will receive
here's the code
```javascript
const displayBirthdate = () => {};
const displayAddress = () => {};
const displayExtraUserInfo = (extra) => {
document.getElementById("btn-birthdate").addEventListener("click", ()=>
{ displayBirthdate(extra) })
document.getElementById("btn-phone").addEventListener("click", () =>
{ displayPhone(extra) })
document.getElementById("btn-address").addEventListener("click", () =>
{ displayAddress(extra) })
```
adding to the above question
this is the expected response passed as parameter extra
{
"results": [
{
"gender": "female",
"name": {
"title": "ms",
"first": "ceyhan",
"last": "dizdar"
},
"location": {
"street": "3826 şehitler cd",
"city": "tekirdağ",
"state": "bitlis",
"postcode": 11689,
"coordinates": {
"latitude": "79.1017",
"longitude": "27.1350"
},
"timezone": {
"offset": "+5:45",
"description": "Kathmandu"
}
},
"email": "ceyhan.dizdar#example.com",
"login": {
"uuid": "34eb65b2-0535-4656-bd68-4da69dc6d016",
"username": "orangefish864",
"password": "grandpa",
"salt": "vowzvAS2",
"md5": "cf4a7f3210ef97e8e72defafd80b94c8",
"sha1": "4f2af3439862b9bf25757ee73df8cd410ce201a2",
"sha256":
"1497acbca446b5fa47d4bc5ffe4e82c17818176596b66d94f213f091c8ed8077"
},
"dob": {
"date": "1979-08-10T22:03:55Z",
"age": 39
},
"registered": {
"date": "2008-05-24T13:30:20Z",
"age": 10
},
"phone": "(873)-801-4132",
"cell": "(751)-606-5317",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/59.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/59.jpg",
"thumbnail":
"https://randomuser.me/api/portraits/thumb/women/59.jpg"
},
"nat": "TR"
}
],
"info": {
"seed": "008a9fe3a638239b",
"results": 1,
"page": 1,
"version": "1.2"
}
}
Now the question is this:
write an arrow function example displayBirthdate(), pass in this object(extra) as a parameter. using de-structuring method, grab the "dob" property in the object(extra).
below is how i have attempted to solve the question:
const displayBirthdate = (obj) =>{
const{results} = obj;
const[{dob}] = results;
}
but it appears to be incorrect. please any help would be appreciated. thank you
const displayBirthdate = ({dob}) => {};
const displayAddress ({location}) =>{};
In your attempted solution, you were trying to obtain the dob object
from results, but const{results} = obj; evaluates results to
an array. const {dob} = results[0]; in my answer gets the dob object from the first element in the results array. Cheers!
const displayBirthdate = (obj) =>{
const{results} = obj;
const[{dob}] = results;
}
const displayBirthdate = (obj) =>{
const {results} = obj;
console.log(results); // this is an array with the required object at index = 0
const {dob} = results[0];
console.log(dob); // dob is the object you are looking for
}

How to add array of ids to entity that doesn't have them

I have my schema set up almost exactly how I want it in redux state, except I want to add an array of form ids to the formTemplate object.
It would look like this:
// Normalized Form Templates
{
1: {
id: '1',
isGlobal: true,
name: 'Form Template Name',
forms: [1, 2], // This is the line I want to add...but how?
},
}
// Normalized Forms
{
1: {
id: '1',
createdAt: '2016-12-28T23:30:13.547Z',
name: 'Form 1',
parentTemplate: '1',
pdfs: [1, 2],
},
2: {
id: '2',
createdAt: '2016-12-28T23:30:13.547Z',
name: 'Form 2',
parentTemplate: '1',
pdfs: [],
},
}
Here is my schema
import { schema } from 'normalizr'
const formTemplate = new schema.Entity('formTemplates', {}, {
processStrategy: value => ({
id: value.id,
name: value.attributes.title,
isGlobal: value.attributes.is_global,
}),
})
const form = new schema.Entity('forms', {
pdfs: [pdf],
}, {
processStrategy: value => ({
id: value.id,
createdAt: value.attributes.created_at,
name: value.attributes.title,
parentTemplate: value.attributes.form_template_id,
pdfs: [...value.relationships.documents.data],
}),
})
const pdf = new schema.Entity('pdfs')
export default {
data: [form],
included: [formTemplate],
}
This is an example of the API response that I'm normalizing
{
"data": [
{
"id": "5",
"type": "provider_forms",
"attributes": {
"title": "Form 1",
"created_at": "2017-01-02T06:00:42.518Z",
"form_template_id": 1
},
"relationships": {
"form_template": {
"data": {
"id": "1",
"type": "form_templates"
}
},
"documents": {
"data": [ // some pdf data here ]
}
}
}
],
"included": [
{
"id": "1",
"type": "form_templates",
"attributes": {
"title": "Form Template",
"created_at": "2016-12-29T22:24:36.201Z",
"updated_at": "2017-01-02T06:00:20.205Z",
"is_global": true
},
}
]
}
You won't be able to do this with Normalizr because the form template entity has no context back to the forms entities. Your actions/reducer need to handle this.
Okay I figured out a way to do this. I changed my formTemplate entity to map them in manually like so:
const formTemplate = new schema.Entity('formTemplates', {}, {
processStrategy: (value, parent) => {
// eslint-disable-next-line eqeqeq
const childrenForms = parent.data.filter(form => form.attributes.form_template_id == value.id)
return {
id: value.id,
name: value.attributes.title,
isGlobal: value.attributes.is_global,
forms: childrenForms.map(form => form.id),
}
},
})

Resources