React native with redux shopping cart - javascript

Am trying to create a shopping cart in react native, my problem is whenever i add a product to the shopping cart it is added through the following action:
export const addToCart = (item) => {
return (dispatch) =>{
dispatch({
type:ADD_TO_CART,
payload: {item}});
}
}
this is the reducer:
import {REMOVE_FROM_CART,ADD_TO_CART,UPDATE_CART_QUANTITY,GET_CATEGORIES, GET_PRODUCTS,
MODAL_STATE,MODAL_STATE_HIDE,ADDRESS_CHANGED,SELECTED_ITEMS} from '../actions/types';
const INITIAL_STATE = {
products:'',
cart:[],
category:'',
isVisible:false,
address:'',
selectedItem:[]
}
export default function(state=INITIAL_STATE, action){
let cart = state.cart;
switch(action.type){
case ADD_TO_CART:
return{...state, cart:[...state.cart, action.payload]}
case REMOVE_FROM_CART:
return{cart:[...state.cart.filter(item => item.id != action.payload)]}
// {...state, cart:[...state.cart.filter((id)=>{ id !== action.payload})]}
case UPDATE_CART_QUANTITY:
return {
...state,
cart: state.cart.map(cart=> cart.id === action.payload.item.id ?
{ ...cart, quantity: action.payload.value} :
cart
)
};
case GET_CATEGORIES:
return{...state, category:action.payload}
case GET_PRODUCTS:
return{...state, products:action.payload}
case MODAL_STATE:
return{...state, isVisible:true}
case MODAL_STATE_HIDE:
return{...state, isVisible:false}
case ADDRESS_CHANGED:
return{...state, address:action.payload}
case SELECTED_ITEMS:
return{...state, selectedItem:[...state.selectedItem, action.payload]}
default:
return state
}
}
BUT when i try to access the cart through mapping state to props in the cart component, it returns undefined is not an object, when console log typeof(cart) from cart component it says its an object:
this is the mapstatetoprops function:
const mapStateToProps = (state) => {
return{
cartItems:state.product_reducer.cart,
modalValue:state.product_reducer.isVisible,
total: state.product_reducer.cart.reduce(
in the array
(accumulatedTotal, cartItem) =>
accumulatedTotal + cartItem.price * cartItem.quantity,
0
)
}
}
this is the json product data that i add to the cart there are two products with 7 and 8 as ids:
{
"product": [
{
"id": 8,
"name": "asad",
"quantity": 1,
"type": "already",
"description": null,
"price": "20000.00",
"ingredients": null,
"deliveryfee": "0.00",
"supplier": null,
"duration": "3",
"category_id": 3,
"created_at": "2020-05-03 15:03:23",
"updated_at": "2020-05-03 15:03:23",
"deleted_at": null,
"photo": {
"id": 19,
"model_type": "App\\Product",
"model_id": 8,
"collection_name": "photo",
"name": "5eaedd370c100_jamies-iced-green-tea",
"file_name": "5eaedd370c100_jamies-iced-green-tea.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 36610,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 19,
"created_at": "2020-05-03 15:03:24",
"updated_at": "2020-05-03 15:03:24",
"url": "http://192.168.0.112/kwenu/storage/app/public/19/5eaedd370c100_jamies-iced-green-tea.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/19/conversions/5eaedd370c100_jamies-iced-green-tea-thumb.jpg"
},
"sliderimages": [],
"tags": [
{
"id": 1,
"name": "Avocado",
"supplier": null,
"created_at": "2020-04-23 09:35:00",
"updated_at": "2020-04-23 09:35:00",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 8,
"product_tag_id": 1
},
"media": []
},
{
"id": 2,
"name": "cushew",
"supplier": "Fruit Salads",
"created_at": "2020-04-27 13:03:35",
"updated_at": "2020-04-27 13:03:35",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 8,
"product_tag_id": 2
},
"media": []
}
],
"media": [
{
"id": 19,
"model_type": "App\\Product",
"model_id": 8,
"collection_name": "photo",
"name": "5eaedd370c100_jamies-iced-green-tea",
"file_name": "5eaedd370c100_jamies-iced-green-tea.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 36610,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 19,
"created_at": "2020-05-03 15:03:24",
"updated_at": "2020-05-03 15:03:24",
"url": "http://192.168.0.112/kwenu/storage/app/public/19/5eaedd370c100_jamies-iced-green-tea.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/19/conversions/5eaedd370c100_jamies-iced-green-tea-thumb.jpg"
}
]
},
{
"id": 7,
"name": "Fruity",
"quantity": 1,
"type": "own",
"description": null,
"price": "18000.00",
"ingredients": null,
"deliveryfee": "0.00",
"supplier": null,
"duration": "1",
"category_id": 2,
"created_at": "2020-05-03 11:06:52",
"updated_at": "2020-05-03 11:06:52",
"deleted_at": null,
"photo": {
"id": 18,
"model_type": "App\\Product",
"model_id": 7,
"collection_name": "photo",
"name": "5eaea5c67a659_grilledchicken",
"file_name": "5eaea5c67a659_grilledchicken.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 13069,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 18,
"created_at": "2020-05-03 11:06:53",
"updated_at": "2020-05-03 11:06:56",
"url": "http://192.168.0.112/kwenu/storage/app/public/18/5eaea5c67a659_grilledchicken.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/18/conversions/5eaea5c67a659_grilledchicken-thumb.jpg"
},
"sliderimages": [],
"tags": [
{
"id": 1,
"name": "Avocado",
"supplier": null,
"created_at": "2020-04-23 09:35:00",
"updated_at": "2020-04-23 09:35:00",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 7,
"product_tag_id": 1
},
"media": []
},
{
"id": 2,
"name": "cushew",
"supplier": "Fruit Salads",
"created_at": "2020-04-27 13:03:35",
"updated_at": "2020-04-27 13:03:35",
"deleted_at": null,
"picture": [],
"pivot": {
"product_id": 7,
"product_tag_id": 2
},
"media": []
}
],
"media": [
{
"id": 18,
"model_type": "App\\Product",
"model_id": 7,
"collection_name": "photo",
"name": "5eaea5c67a659_grilledchicken",
"file_name": "5eaea5c67a659_grilledchicken.jpg",
"mime_type": "image/jpeg",
"disk": "public",
"size": 13069,
"manipulations": [],
"custom_properties": {
"generated_conversions": {
"thumb": true
}
},
"responsive_images": [],
"order_column": 18,
"created_at": "2020-05-03 11:06:53",
"updated_at": "2020-05-03 11:06:56",
"url": "http://192.168.0.112/kwenu/storage/app/public/18/5eaea5c67a659_grilledchicken.jpg",
"thumbnail": "http://192.168.0.112/kwenu/storage/app/public/18/conversions/5eaea5c67a659_grilledchicken-thumb.jpg"
}
]
}
]
}
THE PROBLEM IS INSTEAD OF STATE RETURNING cart AS AN ARRAY OF OBJECTS, IT RETURNS AN OBJECT OF OBJECTS, THANK YOU IN ADVANCE

i see addToCart action take the payload as an object { item }
and you try to access in reducer by action.payload without item
so
you can change
case ADD_TO_CART:
return{...state, cart:[...state.cart, action.payload.item]}
Or just update add to cart to be like so && all actions should be same
export const addToCart = (payload) => {
return (dispatch) =>{
dispatch({
type:ADD_TO_CART,
payload
}
}

Fixed it by changing the name of the cart array in the reducer from
const INITIAL_STATE = {
products:'',
cart:[],
category:'',
isVisible:false,
address:'',
selectedItem:[]
}
to:
const INITIAL_STATE = {
products:'',
carts:[],
category:'',
isVisible:false,
address:'',
selectedItem:[]
}
and the creating a class function for rendering the items in the cart component which i supplied to the renderitem function in the flatlist now the cart returns an array of objects. THANK YOU MUSTAFA FOR YOUR CONCERN

Related

Looping through nested JSON returns NULL

I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?

How can i calculate the rating in the rating array and still return it as a response

This is the sample JSON response from the Backend, the rating is in ratings array and the value is rating, so I want to calculate the average rating for each course and still return it as a response to frontend,
I tried using Object.Assign() but is worked well when i am fetching just one course but when i am fetching all courses, it doesn't work.
please i need help
{
"message": "Fetched successfully",
"status": "Success",
"statusCode": 200,
"data": {
"items": [
{
"id": 210,
"courseUuid": "93b760a7-505e-41bf-b57e-d84ecf53255f",
"userId": 2,
"title": "Complete Angularzero to hero",
"imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655654436946-f02118c8-e3e9-44e5-8913-48d4f45cd816.png",
"slugUrl": "Complete-Angularzero-to-hero-19-06-2022-93b760a7-505e-41bf-b57e-d84ecf53255f",
"amount": "50,600",
"averageRating": "11.5",
"createdAt": "2022-06-19T16:00:43.009Z",
"updatedAt": "2022-06-19T23:27:46.073Z",
"user": {
"id": 2,
"userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
"email": "jessika76#hotmail.com",
"nawisNumber": "NAWIS/2022/54682884"
},
"category": {
"id": 1,
"categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
"name": "Front-End Development",
"slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
},
"duration": {
"id": 23,
"durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
"duration": "5 Months"
},
"enrollments": [
{
"id": 1,
"paymentStatus": "Not Completed",
"createdAt": "2022-06-19T16:04:22.375Z",
"user": {
"id": 3,
"userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
"email": "damion.jacobs84#yahoo.com",
"nawisNumber": "NAWIS/2022/12758991"
}
},
{
"id": 2,
"paymentStatus": "Not Completed",
"createdAt": "2022-06-19T16:07:37.059Z",
"user": {
"id": 6,
"userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
"email": "olaf_bailey#hotmail.com",
"nawisNumber": "NAWIS/2022/11177867"
}
}
],
"ratings": [
{
"id": 1,
"rating": 2,
"review": "some text here",
"createdAt": "2022-06-19T16:04:40.339Z",
"user": {
"id": 3,
"userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
"email": "damion.jacobs84#yahoo.com"
}
},
{
"id": 2,
"rating": 5,
"review": "some text here",
"createdAt": "2022-06-19T16:07:23.798Z",
"user": {
"id": 6,
"userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
"email": "olaf_bailey#hotmail.com"
}
}
]
},
{
"id": 208,
"courseUuid": "16855bd6-dd18-420a-8611-bc77bbda818c",
"userId": 2,
"title": "Complete Vuejs zero to hero",
"imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653347091-cfee6022-0d3a-43e2-b780-986eda2607ed.png",
"slugUrl": "undefined-19-06-2022-16855bd6-dd18-420a-8611-bc77bbda818c",
"amount": "0",
"averageRating": "0",
"createdAt": "2022-06-19T15:42:30.273Z",
"updatedAt": "2022-06-19T15:53:07.726Z",
"user": {
"id": 2,
"userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
"email": "jessika76#hotmail.com",
"nawisNumber": "NAWIS/2022/54682884"
},
"category": {
"id": 1,
"categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
"name": "Front-End Development",
"slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
},
"duration": {
"id": 23,
"durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
"duration": "5 Months"
},
"enrollments": [],
"ratings": []
},
{
"id": 207,
"courseUuid": "bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
"userId": 2,
"title": "Complete Vuejs zero to hero",
"imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653325613-dda17c5c-2a4a-435a-99cb-ad28ea01bbb0.png",
"slugUrl": "Complete-Vuejs-zero-to-hero-19-06-2022-bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
"amount": "50,600",
"averageRating": "0",
"createdAt": "2022-06-19T15:42:12.687Z",
"updatedAt": "2022-06-19T15:42:12.687Z",
"user": {
"id": 2,
"userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
"email": "jessika76#hotmail.com",
"nawisNumber": "NAWIS/2022/54682884"
},
"category": {
"id": 1,
"categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
"name": "Front-End Development",
"slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
},
"duration": {
"id": 23,
"durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
"duration": "5 Months"
},
"enrollments": [],
"ratings": []
}
],
"meta": {
"totalItems": 209,
"itemCount": 3,
"itemsPerPage": 6,
"totalPages": 35,
"currentPage": 1
},
"links": {
"first": "http://ourakademy.com/api/v1/courses?limit=6",
"previous": "",
"next": "http://ourakademy.com/api/v1/courses?page=2&limit=6",
"last": "http://ourakademy.com/api/v1/courses?page=35&limit=6"
}
}
}
Assuming you put your json response in sampleJson variable
let sampleJson = YOUR JSON RESPONE
let sum = 0
let noOfRatings = 0
if(sampleJson && sampleJson.data && sampleJson.data.items){
sampleJson.data.items.forEach(item => {
item.ratings.forEach(i => {
if (i && i.rating) { sum += i.rating; noOfRatings++ }
})
});
if(sum && noOfRatings){
let averateRating = sum / noOfRatings
console.log('Average Rating : ',averateRating)
}
}
You will get average rating using this code.
Hope it helps :)
This is how i fixed the problem
const courses: any = await this.find();
for (let i = 0; i < courses.length; i++) {
const course = courses[i];
const sum: any = course.ratings.reduce((accumulator, object) => {
return accumulator + object.rating;
}, 0);
courses[i] = {
...course,
avg: sum / course.ratings.length,
};
}
return courses;

mongoDB - How do master-detail structure grouped detail collection specific fields summary

In a mongodb database with a master-detail structure, how do I ensure that the data in the detail table is grouped according to the status area while querying the master table. For example ...
Master, Row, Job, Fields, [Detail Status Grouped Count / Summary Object]
Edited:
sms_jobs collection example data is :
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z")
}
sms_job_details collection example data is :
// 1
{
"_id": NumberInt("221462"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "waiting", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 2
{
"_id": NumberInt("221463"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "failed", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 3
{
"_id": NumberInt("221464"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "success", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
I experimented for approximately 4-5 hours. I could get the closest result with the following query.
db.getCollection("sms_jobs").aggregate([{
$lookup: {
from: "sms_job_details",
localField: "_id",
foreignField: "sms_job_id",
as: "data"
}
}, {
$unwind: "$data"
}, {
$group: {
_id: {
id: "$_id",
status: "$data.status"
},
qty: {
$sum: 1
}
}
}, {
$project: {
_id: "$_id.id",
qty: 1,
status: "$_id.status"
}
}])
And get this result :
// 1
{
"qty": 22145,
"_id": NumberInt("4"),
"status": "success"
}
// 2
{
"qty": 1,
"_id": NumberInt("3"),
"status": "success"
}
// 3
{
"qty": 22142,
"_id": NumberInt("1"),
"status": "success"
}
// 4
{
"qty": 1,
"_id": NumberInt("1"),
"status": "failed"
}
// 5
{
"qty": 2,
"_id": NumberInt("1"),
"status": "waiting"
}
// 6
{
"qty": 1,
"_id": NumberInt("3"),
"status": "failed"
}
// 7
{
"qty": 3,
"_id": NumberInt("3"),
"status": "waiting"
}
What do I want ?
The query result I want is as follows.
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z"),
// Added part...
"status_countes": {
"success": NumberInt("20"),
"failed": NumberInt("2"),
"waiting": NumberInt("11"),
"canceled": NumberInt("0"),
"total": NumberInt("33")
},
}
Thank you in advance for your help...

How can I update a specific nested item in my reducer?

I have a reducer with the following structure:
{
"id": 8,
"location_name": "Some place",
"lat": "nn.nnnnnn",
"lng": "-nn.nnnnn",
"review_count": 3,
"score_avg": 3.00,
"reviews": [
{
"id": 14,
"userId": 1,
"userName": "JohnDoe",
"body": "Lorem Ipsum.",
"score": null,
"likes": 2,
"liked": true,
"review_pic": null
},
{
"id": 15,
"userId": 1,
"userName": "JohnDoe",
"body": "Lorem Ipsum.",
"score": null,
"likes": 0,
"liked": false,
"review_pic": null
},
{
"id": 13,
"userId": 4,
"userName": "JohnDoe",
"body": "Lorem Ipsum.",
"score": null,
"likes": 0,
"liked": false,
"review_pic": null
}
]
}
On the other hand, I have an action creator that returns an ID. I am trying to grab this ID to change liked to true and set likes+1 but the nested nature of this reducer's state is tripping me off.
EDIT: here's what I've been trying with my reducer with no luck:
import {GET_REVIEWS, CLEAR_REVIEWS, LIKE} from './reviewTypes';
const initialState = [];
const reviewReducer = (state = initialState, action) => {
switch(action.type) {
case GET_REVIEWS:
return action.payload;
case LIKE:
const reviews = state.reviews.map(review => {
if(review.id === action.payload) {
return {
...review,
liked: true,
likes: review.likes++
}
} else {
return review;
}
});
return {
...state,
reviews
}
case CLEAR_REVIEWS:
return [];
default:
return state;
}
}
export default reviewReducer;
I iterate over array.reviews with Array#some for finding the review with the desired id. If I found it than I increment the likes and set liked on true,
function updateLike(id, array) {
array.reviews.some(review => {
if (review.id==id) {
review.likes++;
review.liked = true;
return true;
}
});
}
let array = {
"id": 8,
"location_name": "Some place",
"lat": "nn.nnnnnn",
"lng": "-nn.nnnnn",
"review_count": 3,
"score_avg": 3.00,
"reviews": [
{
"id": 14,
"userId": 1,
"userName": "JohnDoe",
"body": "Lorem Ipsum.",
"score": null,
"likes": 2,
"liked": true,
"review_pic": null
},
{
"id": 15,
"userId": 1,
"userName": "JohnDoe",
"body": "Lorem Ipsum.",
"score": null,
"likes": 0,
"liked": false,
"review_pic": null
},
{
"id": 13,
"userId": 4,
"userName": "JohnDoe",
"body": "Lorem Ipsum.",
"score": null,
"likes": 0,
"liked": false,
"review_pic": null
}
]
};
updateLike(15, array);
console.log(array);
You can use Array#find to obtain the element with a specific id.
const data = { "id": 8, "location_name": "Some place", "lat": "nn.nnnnnn", "lng": "-nn.nnnnn", "review_count": 3, "score_avg": 3.00, "reviews": [ { "id": 14, "userId": 1, "userName": "JohnDoe", "body": "Lorem Ipsum.", "score": null, "likes": 2, "liked": true, "review_pic": null }, { "id": 15, "userId": 1, "userName": "JohnDoe", "body": "Lorem Ipsum.", "score": null, "likes": 0, "liked": false, "review_pic": null }, { "id": 13, "userId": 4, "userName": "JohnDoe", "body": "Lorem Ipsum.", "score": null, "likes": 0, "liked": false, "review_pic": null } ] };
let id = 13;
let obj = data.reviews.find(x => x.id === id);
if(obj) obj.liked = true;
console.log(data);
You don't have to use a reducer on that one, because u have only one array and you should be fine with useState, this code should work for you.
const onItemLike = (itemID) => {
setState(state.map(x => {
if(reviews.id === itemID)
return {...x, liked: true, likes: state.reviews[x].likes+1}
}))
}

Getting a variable from a multidimentional JSON array using Jquery

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Categories

Resources