USPS not returning correct shipping for these 39 countries - usps

I am trying to processing international shipping requests through the USPS api.
I've found out that these 36 countries(?) do not return a shipping price.
In fact, I cannot seems to find a decent list of countries accepted by the USPS shipping api, there are always countries that return errors.
I tried https://www.iso.org/obp/ui/#search
Any ideas?
Object {country: "Åland Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "American Samoa", shipping_price: false, cart: Object}
products.js:195 Object {country: "Antarctica", shipping_price: false, cart: Object}
products.js:195 Object {country: "Bonaire, Saint Eustatius and Saba", shipping_price: false, cart: Object}
products.js:195 Object {country: "Bouvet Island", shipping_price: false, cart: Object}
products.js:195 Object {country: "British Indian Ocean Territory", shipping_price: false, cart: Object}
products.js:195 Object {country: "Congo, the Democratic Republic of the", shipping_price: false, cart: Object}
products.js:195 Object {country: "Côte d’Ivoire", shipping_price: false, cart: Object}
products.js:195 Object {country: "Cocos (Keeling) Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "French Southern Territories", shipping_price: false, cart: Object}
products.js:195 Object {country: "Heard Island and McDonald Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "Holy See (Vatican City State)", shipping_price: false, cart: Object}
products.js:195 Object {country: "Iran, Islamic Republic of", shipping_price: false, cart: Object}
products.js:195 Object {country: "Lao People’s Democratic Republic", shipping_price: false, cart: Object}
products.js:195 Object {country: "Libyan Arab Jamahiriya", shipping_price: false, cart: Object}
products.js:195 Object {country: "Macedonia, the former Yugoslav Republic of", shipping_price: false, cart: Object}
products.js:195 Object {country: "Micronesia, Federated States of", shipping_price: false, cart: Object}
products.js:195 Object {country: "Moldova, Republic of", shipping_price: false, cart: Object}
products.js:195 Object {country: "Marshall Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "Northern Mariana Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "Palestinian Territory, Occupied", shipping_price: false, cart: Object}
products.js:195 Object {country: "Russian Federation", shipping_price: false, cart: Object}
products.js:195 Object {country: "Saint Barthélemy", shipping_price: false, cart: Object}
products.js:195 Object {country: "Saint Martin (French part)", shipping_price: false, cart: Object}
products.js:195 Object {country: "Sint Maarten (Dutch part)", shipping_price: false, cart: Object}
products.js:195 Object {country: "Somalia", shipping_price: false, cart: Object}
products.js:195 Object {country: "Saint Helena, Ascension and Tristan da Cunha", shipping_price: false, cart: Object}
products.js:195 Object {country: "South Georgia and the South Sandwich Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "Svalbard and Jan Mayen", shipping_price: false, cart: Object}
products.js:195 Object {country: "Syrian Arab Republic", shipping_price: false, cart: Object}
products.js:195 Object {country: "Tanzania, United Republic of", shipping_price: false, cart: Object}
products.js:195 Object {country: "Taiwan, Province of China", shipping_price: false, cart: Object}
products.js:195 Object {country: "United States Minor Outlying Islands", shipping_price: false, cart: Object}
products.js:195 Object {country: "Virgin Islands, British", shipping_price: false, cart: Object}
products.js:195 Object {country: "Virgin Islands, U.S.", shipping_price: false, cart: Object}
products.js:195 Object {country: "Wallis and Futuna", shipping_price: false, cart: Object}
products.js:195 Object {country: "Western Sahara", shipping_price: false, cart: Object}
products.js:195 Object {country: "Yemen", shipping_price: false, cart: Object}
products.js:195 Object {country: "Venezuela, Bolivarian Republic of", shipping_price: false, cart: Object}
I did another list of countries while removing the parenthesis and came up with this list of failed countries:
Countries Failed:
Åland Islands
American Samoa
Antarctica
Bosnia and Herzegovina
Bonaire, Sint Eustatius and Saba
Bouvet Island
British Indian Ocean Territory
Cabo Verde
Cocos
Curaçao
Côte d'Ivoire
French Southern Territories
Falkland Islands (the) [Malvinas]
Guam
Heard Island and McDonald Islands
Holy See
Lao People's Democratic Republic
Marshall Islands
Micronesia
Palau
Northern Mariana Islands
Palestine, State of
Pitcairn
Puerto Rico
Russian Federation
Réunion
Saint Barthélemy
Saint Helena, Ascension and Tristan da Cunha
Somalia
South Sudan
South Georgia and the South Sandwich Islands
Svalbard and Jan Mayen
Syrian Arab Republic
Tanzania, United Republic of
United States Minor Outlying Islands
United Kingdom of Great Britain and Northern Ireland
Wallis and Futuna
Western Sahara*
United States of America
Yemen

This is the best list of accepted USPS locale names that I have found.
Many of the entries on your list can be found here with their correct wording.
Some (such as Svalbard) are not on the list.
Some are still broken even when using the name-form listed.
http://pe.usps.com/text/Imm/immctry.htm
Update
If you use the USPS names from the link above, the following will still fail (workarounds, if any, are included):
Cote d’Ivoire: replace "’" with space or use "Ivory Coast"
Channel Islands (Jersey, Guernsey, Alderney, and Sark) (Great Britain and Northern Ireland): remove comma after "Alderney", or use individual island names
East Timor (Timor-Leste): Use "East Timor" or "Timor-Leste"
Guinea–Bissau: Replace n dash with hyphen
Ivory Coast (Cote d’Ivoire): see above
Korea, Democratic People’s Republic of (North Korea): use "North Korea"
Also, some (Guatemala, Somalia, Syria, Yemen) will return errors explaining that there is no USPS service to that country.

Related

Popular a field of a schema with a schema that is inside an array (Moongose)

I need to obtain the data referring to the city_id which is a Schema, which is linked to an array of another Schema.
This is the Schema called Companies and I need to get information about the city
{
"_id": "5fa1484a34a032ac5687b1c2",
"name": "Company",
"address": "Address",
"email": "email#email.com",
"phone": 123456789,
"city_id": "5fa147b607f466ac1d536bd0",
"__v": 0
},
Now, this is the City Schema. I have a Location Schema and this contains a Country relation:
import Country from './countrySchema';
const locationSchema = new Schema({
region: {
type: String,
required: true,
unique: true,
dropDups: true
},
locations: [Country.schema]
},{ timestamps: true});
const locationModel = model("Location", locationSchema);
This is the Country Schema and this contains a City relation:
import City from './CitySchema';
const countrySchema = new Schema({
country_name: {
type: String,
required: true,
unique: true,
dropDups: true
},
cities: [City.schema]
},{ _id: true, timestamps: true });
const countryModel = model("Country", countrySchema);
This is the City Schema:
const citySchema = new Schema({
city_name: {
type: String,
required: true,
unique: true,
dropDups: true
}
},{ _id: true, timestamps: true });
const cityModel = model("City", citySchema);
Finally, This looks like :
"_id": "5fa147b607f466ac1d536bce",
"locations": [
{
"_id": "5fa147b607f466ac1d536bcf",
"country_name": "Colombia",
"cities": [
{
"_id": "5fa147b607f466ac1d536bd0",
"city_name": "Medellín",
"createdAt": "2020-11-03T12:06:14.914Z",
"updatedAt": "2020-11-03T12:06:14.914Z"
},
{
"_id": "5fa147b607f466ac1d536bd1",
"city_name": "Bogotá",
"createdAt": "2020-11-03T12:06:14.914Z",
"updatedAt": "2020-11-03T12:06:14.914Z"
}
],
"createdAt": "2020-11-03T12:06:14.914Z",
"updatedAt": "2020-11-03T12:06:14.914Z"
},
How can I get the city information?? Thanks so much.
Try this one:
locationModel.findOne({_id:"5fa147b607f466ac1d536bce"})
.populate({ path:"locations",{path:"cities"}})
.exec((err,location) => {
if(err) reject(err);
return resolve(location);
})`

how to check if a 2d array of strings contains more than 1 word?

I have a 2d array of country names, C, and a struct type list called countries with one member, country.
if C[i] contains more than 2 words, I want to ignore C[i];
if C[i] contains one word, I want to store that country name C[i] in countries[i].country.
my program is not working. what am I doing wrong?
//
// main.c
// delete 2 words
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <string.h>
typedef struct list{
char country[50];
}list;
int main(void) {
list countries[100];
int len=0, i=0, j=0;
char C[][100] = {"United States", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and/or Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Cook Islands", "Costa Rica", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecudaor", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France, Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kosovo", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfork Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia South Sandwich Islands", "South Sudan", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbarn and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States minor outlying islands", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City State", "Venezuela", "Vietnam", "Virigan Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zaire", "Zambia", "Zimbabwe"};
while (C[i] != NULL){
for (j = 0; j < strlen(C[i]) - 1; ++j){
if (C[i][j] == ' '){
i = i + 1;
}
else if (C[i][j] == '\0'){
i = i + 1;
}
else{
strcpy(C[i], countries[i].country);
i = i + 1;
}
}
}
len = i;
printf("%d", len);
for (i = 0; i < len; ++i){
printf("%s", countries[i].country);
}
return 0;
}
If you scan for a NULL, you need to end your list with a NULL, but you need an array of pointers not a 2D array
You swap the order of the strcpy parameters
Your code is too complicated, the standard library can help you, in this case you can use strchr
#include <stdio.h>
#include <string.h>
typedef struct list
{
char country[50];
} list;
int main(void)
{
list countries[100];
int len = 0;
const char *C[] = {"United States", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", NULL};
for (int i = 0; C[i] != NULL; i++)
{
char *ptr = strchr(C[i], ' ');
if (ptr != NULL)
{
strcpy(countries[len++].country, C[i]);
}
}
printf("%d\n", len);
for (int i = 0; i < len; i++)
{
printf("%s\n", countries[i].country);
}
return 0;
}
If the string is not going to be modified, you can also use a pointer for the country member:
#include <stdio.h>
#include <string.h>
typedef struct list
{
char *country;
} list;
int main(void)
{
list countries[100];
int len = 0;
char *C[] = {"United States", "Canada", "Afghanistan", "Albania", "Algeria", "American Samoa", NULL};
for (int i = 0; C[i] != NULL; i++)
{
char *ptr = strchr(C[i], ' ');
if (ptr != NULL)
{
countries[len++].country = C[i];
}
}
printf("%d\n", len);
for (int i = 0; i < len; i++)
{
printf("%s\n", countries[i].country);
}
return 0;
}
The condition of the loop
while (C[i] != NULL){
does not make sense because the array is not an array of pointers,
In this call of strcpy
strcpy(C[i], countries[i].country);
the order of arguments is incorrect.
Pay attention to that in general a string can contain adjacent or leading or trailing blanks. So the approach with using strchr is just bad.
You could write a separate function that will count the number of words in a string.
Here is a demonstrative program.
//
// main.c
// delete 2 words
#include <stdio.h>
#include <string.h>
enum { LENGTH = 50 };
typedef struct list
{
char country[LENGTH];
} list;
size_t count_words( const char *s )
{
const char *delim = " \t";
size_t n = 0;
while ( *s )
{
s += strspn( s, delim );
if ( *s ) ++n;
s += strcspn( s , delim );
}
return n;
}
int main(void)
{
char C[][LENGTH] =
{
"United States", "Canada", "Afghanistan", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
"Antigua and/or Barbuda", "Argentina", "Armenia", "Aruba",
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana",
"Bouvet Island", "Brazil", "British Indian Ocean Territory",
"Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia",
"Cameroon", "Cape Verde", "Cayman Islands", "Central African Republic",
"Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
"Colombia", "Comoros", "Congo", "Cook Islands", "Costa Rica",
"Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark",
"Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecudaor",
"Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
"Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji",
"Finland", "France", "France, Metropolitan", "French Guiana",
"French Polynesia", "French Southern Territories", "Gabon", "Gambia",
"Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland",
"Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard and Mc Donald Islands", "Honduras", "Hong Kong",
"Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)",
"Iraq", "Ireland", "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan",
"Jordan", "Kazakhstan", "Kenya", "Kiribati",
"Korea, Democratic People's Republic of", "Korea, Republic of", "Kosovo",
"Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia",
"Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya",
"Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia",
"Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte",
"Mexico", "Micronesia, Federated States of", "Moldova, Republic of",
"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar",
"Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
"New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
"Norfork Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan",
"Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion",
"Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino",
"Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "South Georgia South Sandwich Islands",
"South Sudan", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon",
"Sudan", "Suriname", "Svalbarn and Jan Mayen Islands", "Swaziland",
"Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan",
"Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga",
"Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine",
"United Arab Emirates", "United Kingdom",
"United States minor outlying islands", "Uruguay", "Uzbekistan", "Vanuatu",
"Vatican City State", "Venezuela", "Vietnam", "Virigan Islands (British)",
"Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara",
"Yemen", "Yugoslavia", "Zaire", "Zambia", "Zimbabwe"
};
const size_t M = sizeof( C ) / sizeof( *C );
enum { N = 100 };
list countries[M];
size_t n = 0;
for ( size_t i = 0; i < M && n < N; i++ )
{
if ( count_words( C[i] ) == 1 ) strcpy(countries[n++].country, C[i] );
}
for ( size_t i = 0, j = 0; i < n; i++ )
{
printf( "\"%s\" ", countries[i].country );
if ( ( j = ( j + 1 ) % 4 ) == 0 ) putchar( '\n' );
}
return 0;
}
The program output is
"Canada" "Afghanistan" "Albania" "Algeria"
"Andorra" "Angola" "Anguilla" "Antarctica"
"Argentina" "Armenia" "Aruba" "Australia"
"Austria" "Azerbaijan" "Bahamas" "Bahrain"
"Bangladesh" "Barbados" "Belarus" "Belgium"
"Belize" "Benin" "Bermuda" "Bhutan"
"Bolivia" "Botswana" "Brazil" "Bulgaria"
"Burundi" "Cambodia" "Cameroon" "Chad"
"Chile" "China" "Colombia" "Comoros"
"Congo" "Cuba" "Cyprus" "Denmark"
"Djibouti" "Dominica" "Ecudaor" "Egypt"
"Eritrea" "Estonia" "Ethiopia" "Fiji"
"Finland" "France" "Gabon" "Gambia"
"Georgia" "Germany" "Ghana" "Gibraltar"
"Greece" "Greenland" "Grenada" "Guadeloupe"
"Guam" "Guatemala" "Guinea" "Guinea-Bissau"
"Guyana" "Haiti" "Honduras" "Hungary"
"Iceland" "India" "Indonesia" "Iraq"
"Ireland" "Israel" "Italy" "Jamaica"
"Japan" "Jordan" "Kazakhstan" "Kenya"
"Kiribati" "Kosovo" "Kuwait" "Kyrgyzstan"
"Latvia" "Lebanon" "Lesotho" "Liberia"
"Liechtenstein" "Lithuania" "Luxembourg" "Macau"
"Macedonia" "Madagascar" "Malawi" "Malaysia"
"Maldives" "Mali" "Malta" "Martinique"
As you can see from the program output it seems that the number of elements in the array of structures that is 100 is not enough to accommodate all strings with one word. You should enlarge it. It should have at least 168 elements for the given list of countries.
For example you could at first count the number of strings with one word and then declare a variable length array of structures with the number of elements equal to the found number of strings.
Here is an updated version of the demonstrative program with a variable length array of structures.
//
// main.c
// delete 2 words
#include <stdio.h>
#include <string.h>
enum { LENGTH = 50 };
typedef struct list
{
char country[LENGTH];
} list;
size_t count_words( const char *s )
{
const char *delim = " \t";
size_t n = 0;
while ( *s )
{
s += strspn( s, delim );
if ( *s ) ++n;
s += strcspn( s , delim );
}
return n;
}
int main(void)
{
char C[][LENGTH] =
{
"United States", "Canada", "Afghanistan", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
"Antigua and/or Barbuda", "Argentina", "Armenia", "Aruba",
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana",
"Bouvet Island", "Brazil", "British Indian Ocean Territory",
"Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia",
"Cameroon", "Cape Verde", "Cayman Islands", "Central African Republic",
"Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
"Colombia", "Comoros", "Congo", "Cook Islands", "Costa Rica",
"Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark",
"Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecudaor",
"Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
"Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji",
"Finland", "France", "France, Metropolitan", "French Guiana",
"French Polynesia", "French Southern Territories", "Gabon", "Gambia",
"Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland",
"Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard and Mc Donald Islands", "Honduras", "Hong Kong",
"Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)",
"Iraq", "Ireland", "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan",
"Jordan", "Kazakhstan", "Kenya", "Kiribati",
"Korea, Democratic People's Republic of", "Korea, Republic of", "Kosovo",
"Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia",
"Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya",
"Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia",
"Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte",
"Mexico", "Micronesia, Federated States of", "Moldova, Republic of",
"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar",
"Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
"New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue",
"Norfork Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan",
"Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion",
"Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino",
"Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "South Georgia South Sandwich Islands",
"South Sudan", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon",
"Sudan", "Suriname", "Svalbarn and Jan Mayen Islands", "Swaziland",
"Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan", "Tajikistan",
"Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga",
"Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine",
"United Arab Emirates", "United Kingdom",
"United States minor outlying islands", "Uruguay", "Uzbekistan", "Vanuatu",
"Vatican City State", "Venezuela", "Vietnam", "Virigan Islands (British)",
"Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara",
"Yemen", "Yugoslavia", "Zaire", "Zambia", "Zimbabwe"
};
const size_t M = sizeof( C ) / sizeof( *C );
size_t n = 0;
for ( size_t i = 0; i < M; i++ )
{
if ( count_words( C[i] ) == 1 ) ++n;
}
list countries[n];
for ( size_t i = 0, j = 0; i < M; i++ )
{
if ( count_words( C[i] ) == 1 ) strcpy(countries[j++].country, C[i] );
}
for ( size_t i = 0, j = 0; i < n; i++ )
{
printf( "\"%s\" ", countries[i].country );
if ( ( j = ( j + 1 ) % 4 ) == 0 ) putchar( '\n' );
}
return 0;
}
Now the program output is
"Canada" "Afghanistan" "Albania" "Algeria"
"Andorra" "Angola" "Anguilla" "Antarctica"
"Argentina" "Armenia" "Aruba" "Australia"
"Austria" "Azerbaijan" "Bahamas" "Bahrain"
"Bangladesh" "Barbados" "Belarus" "Belgium"
"Belize" "Benin" "Bermuda" "Bhutan"
"Bolivia" "Botswana" "Brazil" "Bulgaria"
"Burundi" "Cambodia" "Cameroon" "Chad"
"Chile" "China" "Colombia" "Comoros"
"Congo" "Cuba" "Cyprus" "Denmark"
"Djibouti" "Dominica" "Ecudaor" "Egypt"
"Eritrea" "Estonia" "Ethiopia" "Fiji"
"Finland" "France" "Gabon" "Gambia"
"Georgia" "Germany" "Ghana" "Gibraltar"
"Greece" "Greenland" "Grenada" "Guadeloupe"
"Guam" "Guatemala" "Guinea" "Guinea-Bissau"
"Guyana" "Haiti" "Honduras" "Hungary"
"Iceland" "India" "Indonesia" "Iraq"
"Ireland" "Israel" "Italy" "Jamaica"
"Japan" "Jordan" "Kazakhstan" "Kenya"
"Kiribati" "Kosovo" "Kuwait" "Kyrgyzstan"
"Latvia" "Lebanon" "Lesotho" "Liberia"
"Liechtenstein" "Lithuania" "Luxembourg" "Macau"
"Macedonia" "Madagascar" "Malawi" "Malaysia"
"Maldives" "Mali" "Malta" "Martinique"
"Mauritania" "Mauritius" "Mayotte" "Mexico"
"Monaco" "Mongolia" "Montserrat" "Morocco"
"Mozambique" "Myanmar" "Namibia" "Nauru"
"Nepal" "Netherlands" "Nicaragua" "Niger"
"Nigeria" "Niue" "Norway" "Oman"
"Pakistan" "Palau" "Panama" "Paraguay"
"Peru" "Philippines" "Pitcairn" "Poland"
"Portugal" "Qatar" "Reunion" "Romania"
"Rwanda" "Samoa" "Senegal" "Seychelles"
"Singapore" "Slovakia" "Slovenia" "Somalia"
"Spain" "Sudan" "Suriname" "Swaziland"
"Sweden" "Switzerland" "Taiwan" "Tajikistan"
"Thailand" "Togo" "Tokelau" "Tonga"
"Tunisia" "Turkey" "Turkmenistan" "Tuvalu"
"Uganda" "Ukraine" "Uruguay" "Uzbekistan"
"Vanuatu" "Venezuela" "Vietnam" "Yemen"
"Yugoslavia" "Zaire" "Zambia" "Zimbabwe"

Unable to covert a JSON parsed response into an array

I am using the TMDb API to get data for my program in VB and I am trying to get an array of all the ids of the movies returned from the raw response of JSON, but it keeps coming up with an error. my code is in VB.net and my code looks like this:
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class TMDb_Connection
Private API_Key As String = "my api key"
Private API_url As String = "https://api.themoviedb.org/3"
Private API_Image_Base_url As String = "https://image.tmdb.org/t/p/w500/"
Private API_Pagination As String = "1"
Public Sub SearchAPI(ByVal API_Query As String, ByVal ObjectToken As String)
Dim Response As HttpWebResponse
Dim postData As String = "api_key=" & API_Key & "&query=" & WebUtility.UrlEncode(API_Query)
Dim Request As HttpWebRequest = DirectCast(HttpWebRequest.Create(API_url & "/search/movie?" & postData), HttpWebRequest)
Request.Method = "GET"
Try
Response = DirectCast(Request.GetResponse(), HttpWebResponse)
Dim Stream As Stream = Response.GetResponseStream()
Dim reader As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
Response.Close()
Dim obj = JObject.Parse(responseFromServer)
Dim obj2 As String = JObject.Parse(obj.SelectToken("results"))
MsgBox(obj.SelectToken(ObjectToken))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
and here is the raw response of JSON that I receive from the TMDb API. Here is the link to any details on the API if needed
{
"page": 1,
"total_results": 22,
"total_pages": 2,
"results": [
{
"popularity": 36.796,
"vote_count": 18368,
"video": false,
"poster_path": "/4GpwvwDjgwiShr1UBJIn5fk1gwT.jpg",
"id": 550,
"adult": false,
"backdrop_path": "/pCUdYAaarKqY2AAUtV6xXYO8UGY.jpg",
"original_language": "en",
"original_title": "Fight Club",
"genre_ids": [
18
],
"title": "Fight Club",
"vote_average": 8.4,
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"release_date": "1999-10-15"
},
{
"popularity": 5.124,
"vote_count": 23,
"video": false,
"poster_path": "/iI9c8XNdPuwB4RYbHMd62QNhoRK.jpg",
"id": 440777,
"adult": false,
"backdrop_path": "/qziKhMyrVqj567jlbj55GpBdKf9.jpg",
"original_language": "en",
"original_title": "Female Fight Club",
"genre_ids": [
28
],
"title": "Female Fight Club",
"vote_average": 5.4,
"overview": "A former fighter reluctantly returns to the life she abandoned in order to help her sister survive the sadistic world of illegal fighting and the maniac who runs it.",
"release_date": "2017-03-16"
},
{
"popularity": 2.713,
"vote_count": 0,
"video": false,
"poster_path": null,
"id": 259016,
"adult": false,
"backdrop_path": null,
"original_language": "en",
"original_title": "Insane Fight Club",
"genre_ids": [
99
],
"title": "Insane Fight Club",
"vote_average": 0,
"overview": "A group of friends have created a brand new subculture that is taking over the streets of Glasgow. They've established their very own fight club, but this is no ordinary wrestling event - this is brutal, riotous chaos. Fights don't always stay inside the ring, people are bounced off the side of buses and thrown off balconies in pubs. They now plan the biggest show of their lives. The stakes are high, will it bring them the fame and recognition they need to survive?",
"release_date": "2014-03-11"
},
{
"popularity": 1.864,
"id": 466848,
"video": false,
"vote_count": 18,
"vote_average": 7.1,
"title": "Superhero Fight Club",
"release_date": "2015-04-13",
"original_language": "en",
"original_title": "Superhero Fight Club",
"genre_ids": [
28,
878
],
"backdrop_path": "/u0a4CSy73GP11wVPz8hm0tHQwci.jpg",
"adult": false,
"overview": "Oliver introduces Barry to his own little fight club which features such members as Roy Harper, Laurel Lance, Malcolm Merlyn and Ra's Al Ghul.",
"poster_path": "/zjPn7JUg2tsxlRWp4luK0YVX48Y.jpg"
},
{
"popularity": 1.299,
"vote_count": 8,
"video": false,
"poster_path": "/aXFmWfWYCCxQTkCn7K86RvDiMHZ.jpg",
"id": 347807,
"adult": false,
"backdrop_path": null,
"original_language": "hi",
"original_title": "Fight Club: Members Only",
"genre_ids": [
28
],
"title": "Fight Club: Members Only",
"vote_average": 3.5,
"overview": "Four friends head off to Bombay and get involved in the mother and father of all gang wars.",
"release_date": "2006-02-17"
},
{
"popularity": 1.264,
"id": 104782,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Florence Fight Club",
"release_date": "2010-01-01",
"original_language": "en",
"original_title": "Florence Fight Club",
"genre_ids": [
28,
53
],
"backdrop_path": null,
"adult": false,
"overview": "Four men decided to enter in the oldest Fight Club of the History, The Florentine Football tournament. A father and son, a black guy, an old champion and outsider clerk will enter in an arena of the time to win their fears, to go over their limits, to be heroes for a day.",
"poster_path": null
},
{
"popularity": 2.017,
"vote_count": 19,
"video": false,
"poster_path": "/uvBmJX04cmOtpEHZmY2MBoAwuVn.jpg",
"id": 289732,
"adult": false,
"backdrop_path": null,
"original_language": "zh",
"original_title": "Zombie Fight Club",
"genre_ids": [
28,
27
],
"title": "Zombie Fight Club",
"vote_average": 3.5,
"overview": "It's the end of the century at a corner of the city in a building riddled with crime - Everyone in the building has turned into zombies. After Jenny's boyfriend is killed in a zombie attack, she faces the challenge of surviving in the face of adversity. In order to stay alive, she struggles with Andy to flee danger.",
"release_date": "2014-10-23"
},
{
"popularity": 4.224,
"vote_count": 0,
"video": false,
"poster_path": null,
"id": 322772,
"adult": false,
"backdrop_path": null,
"original_language": "en",
"original_title": "Insane Fight Club II - This Time It’s Personal",
"genre_ids": [
99
],
"title": "Insane Fight Club II - This Time It’s Personal",
"vote_average": 0,
"overview": "Insane Fight Club is back. This year the boys are taking their unique form of entertainment to England as they stage fight nights in Birmingham, Leeds, Liverpool and Newcastle.",
"release_date": "2015-01-21"
},
{
"popularity": 0.6,
"id": 289100,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Girls Fight Club",
"release_date": "2009-06-18",
"original_language": "en",
"original_title": "Girls Fight Club",
"genre_ids": [],
"backdrop_path": null,
"adult": false,
"overview": "The best women's wrestling competition of all time...and if you think it's fake you're in for a big surprise See LEGENDARY Mixed Martial Arts fighters coach their teams to victory in the cage! aka Chuck Lidell's Girl's Fight Club",
"poster_path": null
},
{
"popularity": 1.07,
"vote_count": 5,
"video": false,
"poster_path": null,
"id": 51021,
"adult": false,
"backdrop_path": null,
"original_language": "en",
"original_title": "Lure: Teen Fight Club",
"genre_ids": [
28,
80,
18
],
"title": "Lure: Teen Fight Club",
"vote_average": 3,
"overview": "A community is under siege as three Belmont Highschool coed students go missing with no trace of their whereabouts. The pressure is on the police to capture the culprits responsible. Scouring the school hallways in search of clues, undercover female detective Maggie Rawdon (Jessica Sonnerborn) enters Belmont High as a transfer student in an attempt to solve the hideous disappearance of the students. Maggie makes a few new friends, and gets invited to a private rave in the country. Just as the group begins to suspect that they've taken a wrong turn, however, the trap is sprung and Maggie finds out firsthand what fate has befallen the missing girls.",
"release_date": "2010-11-16"
},
{
"popularity": 0.6,
"vote_count": 3,
"video": false,
"poster_path": null,
"id": 151912,
"adult": false,
"backdrop_path": null,
"original_language": "en",
"original_title": "Jurassic Fight Club",
"genre_ids": [
99
],
"title": "Jurassic Fight Club",
"vote_average": 6.7,
"overview": "Jurassic Fight Club, a paleontology-based miniseries that ran for 12 episodes, depicts how prehistoric beasts hunted their prey, dissecting these battles and uncovering a predatory world far more calculated and complex than originally thought. It was hosted by George Blasing, a self-taught paleontologist.",
"release_date": "2008-10-22"
},
{
"popularity": 0.6,
"id": 600819,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Fight Club: Des Moines",
"release_date": "2018-03-04",
"original_language": "en",
"original_title": "Fight Club: Des Moines",
"genre_ids": [],
"backdrop_path": null,
"adult": false,
"overview": "What if Tyler Durden came to Des Moines, Iowa? This might be what it would look like.",
"poster_path": null
},
{
"popularity": 0.6,
"id": 532155,
"video": false,
"vote_count": 1,
"vote_average": 7,
"title": "Musangwe: Fight Club",
"release_date": "",
"original_language": "en",
"original_title": "Musangwe: Fight Club",
"genre_ids": [],
"backdrop_path": null,
"adult": false,
"overview": "The first rule is that there are no rules. For the bare-knuckle combatants competing in Musangwe fights, anything goes - you can even put a curse on him. The sport, which dates back centuries, has become a South African institution. Any male from the age of nine to ninety can compete. We follow a group of fighters as they slug it out in the ring. Who will be this year's champion?",
"poster_path": "/tZDxttt0LfgAKwvLIWyOO3fr01c.jpg"
},
{
"popularity": 0.6,
"id": 295477,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Fight club camp kusse",
"release_date": "2005-08-12",
"original_language": "da",
"original_title": "Fight club camp kusse",
"genre_ids": [],
"backdrop_path": null,
"adult": false,
"overview": "",
"poster_path": "/4kQyWM9i2UwLcbScNeIn1YTm7HT.jpg"
},
{
"popularity": 0.6,
"vote_count": 0,
"video": false,
"poster_path": "/yrOE92bDvzClGDpsDu8JkUssuuA.jpg",
"id": 488671,
"adult": false,
"backdrop_path": "/A34w8ugqo1i9lah6nOgQONocs0D.jpg",
"original_language": "da",
"original_title": "Comedy Fight Club Live",
"genre_ids": [
35
],
"title": "Comedy Fight Club Live",
"vote_average": 0,
"overview": "",
"release_date": "2017-04-03"
},
{
"popularity": 0.6,
"genre_ids": [
99
],
"video": false,
"vote_count": 1,
"original_language": "en",
"adult": false,
"title": "Brooklyn Girls Fight Club",
"original_title": "Brooklyn Girls Fight Club",
"backdrop_path": null,
"id": 209599,
"vote_average": 7,
"overview": "From the birthplace of boxing legend Mike Tyson, young women brawl in secret fight clubs to win $1000 and invaluable street cred.",
"poster_path": null
},
{
"popularity": 0.6,
"id": 468371,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Nixon Newell: First Female of Fight Club",
"release_date": "2017-07-26",
"original_language": "en",
"original_title": "Nixon Newell: First Female of Fight Club",
"genre_ids": [
99
],
"backdrop_path": null,
"adult": false,
"overview": "Since 2013, Nixon Newell has travelled the world as a professional wrestler. This is the story of her goodbye to independent wrestling.",
"poster_path": null
},
{
"popularity": 1.4,
"id": 615408,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Fight Club But With Tennis And No Fight",
"release_date": "2019-07-13",
"original_language": "en",
"original_title": "Fight Club But With Tennis And No Fight",
"genre_ids": [
16,
35
],
"backdrop_path": null,
"adult": false,
"overview": "Drama descends upon two tennis-obsessed women as the tension moves from off the court and into the café.",
"poster_path": "/8pEQqVtSpgCtb7dzhR55EO1dC3l.jpg"
},
{
"popularity": 0.6,
"vote_count": 0,
"video": false,
"poster_path": null,
"id": 653285,
"adult": false,
"backdrop_path": null,
"original_language": "en",
"original_title": "Fight Club Pro Project Mayhem VIII Night One",
"genre_ids": [],
"title": "Fight Club Pro Project Mayhem VIII Night One",
"vote_average": 0,
"overview": "The rivalry between Fight Club: PRO management and the Schadenfreude faction led by Tipton’s Chris Brookes ended in stunning fashion across both nights of the promotion’s eighth annual Project Mayhem weekender. Night one events followed by a second night of action.",
"release_date": "2019-09-27"
},
{
"popularity": 0.6,
"vote_count": 0,
"video": false,
"poster_path": null,
"id": 653286,
"adult": false,
"backdrop_path": null,
"original_language": "en",
"original_title": "Fight Club Pro Project Mayhem VIII Night Two",
"genre_ids": [],
"title": "Fight Club Pro Project Mayhem VIII Night Two",
"vote_average": 0,
"overview": "The rules saw participants enter in staggered intervals, with the last person due to enter being Wolverhampton’s Trent Seven. However the WWE superstar never made it to the ring, ultimately being thrown off the entrance stage and through a table. Fight Club: PRO wouldn’t be disadvantaged for long, with Jimmy Havoc making yet another surprise appearance at Project Mayhem, to aid the promotion. Birmingham’s Dan Moloney would ultimately secure the pinfall for Fight Club: PRO, piledriving Kyle Fletcher through a table.",
"release_date": "2019-09-28"
}
]
}`
The error message I get is
'cannot convert array to string'
Note: My API key has a string value placeholdeR as the key should be kept totally private, in my program, it has its true value rather than this placeholder
Your results are in an array - a list of Movies.
Try changing the type on this from As String to As JObject and then working with the results from there.
Dim obj2 As String = JObject.Parse(obj.SelectToken("results"))
I have solved this problem with the help of This Youtube video, my amended code is as follows
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class TMDb_Connection
Private API_Key As String = "My API key here"
Private API_url As String = "https://api.themoviedb.org/3"
Private API_Image_Base_url As String = "https://image.tmdb.org/t/p/w500/"
Private API_Pagination As String = "1"
Public Sub SearchAPI(ByVal API_Query As String, ByVal ObjectToken As String)
Dim Response As HttpWebResponse
Dim postData As String = "api_key=" & API_Key & "&query=" & WebUtility.UrlEncode(API_Query)
Dim Request As HttpWebRequest = DirectCast(HttpWebRequest.Create(API_url & "/search/movie?" & postData), HttpWebRequest)
Request.Method = "GET"
Try
Response = DirectCast(Request.GetResponse(), HttpWebResponse)
Dim Stream As Stream = Response.GetResponseStream()
Dim reader As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
Response.Close()
Dim obj As JObject = JObject.Parse(responseFromServer)
Dim objarray As JArray = JArray.Parse(obj.SelectToken("results").ToString)
Dim temp As String = ""
For Each results As JObject In objarray
temp = temp & results.SelectToken("id").ToString() & ", "
Next
MsgBox(temp)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
this code will create a message box with all the IDs of the movies printed out in order. It seems the JSON parse was attempting to parse each id of each movie but could not because it was not in the array, although I still don't fully understand it myself. I hope this helps anyone who comes across this and feel free to ask any more questions, although I am not guaranteed to know the answer! Thank you also very much to the rest of the people who helped me out too!

How to extend an ArrayInput to iterate on properties of an object

I have an API response like this:
{ ...
"schedule":
{
"0": {"endTime": "15:00", "isHoliday": true, "startTime": "14:00"},
"1": {"endTime": "15:00", "isHoliday": false, "startTime": "14:00"},
"2": {"endTime": "15:00", "isHoliday": true, "startTime": "14:00"},
"3": {"endTime": "15:00", "isHoliday": false, "startTime": "14:00"},
"4": {"endTime": "15:00", "isHoliday": true, "startTime": "14:00"},
"5": {"endTime": "15:00", "isHoliday": true, "startTime": "14:00"},
"6": {"endTime": "15:00", "isHoliday": false, "startTime": "14:00"}
}
}
I need an input that iterates over schedule properties.
The closest one is an ArrayInput component which iterates over array elements, but not object keys.
Can someone give a clue on how to write it?
Why not map the schedules:
import { Edit, ArrayInput, SimpleFormIterator, BooleanInput, TextInput } from 'react-admin';
const PointEdit = props => {
const schedule = Object.values(props.schedule)
return (
<Edit schedules={schedules}>
<ArrayInput source="schedules">
<SimpleFormIterator>
<TextInput label="Start Time" source="startTime"/>
<TextInput label="End Time" source="endTime"/>
<BooleanInput label="Holiday" source="isHoliday" />
</SimpleFormIterator>
</ArrayInput>
</Edit>
)
}

Object spread doesn't copy the object properly

I am having a strange issue using object spread. Here is my code:
const AuthenticationReducer = (state = {
authenticationObj: {
"isAuthenticating": true, "isAuthentic": false, "subscriberId": "NA", "username": "NA",
"firstName": "NA", "lastName": "NA", "enabled": "1", "email": "NA", isAuthorized: false
}, lastPasswordCheckStatus: undefined, isSuccessfulChangePassword:undefined,loginUserCheckStatus: undefined, createUserCheckstatus: undefined,
confirmUserCheckstatus: undefined, isSuccessfulChangeEmail:undefined, userContactInfo: {
country: undefined,
address1:undefined,
address2:undefined,
city:undefined,
postalCode:undefined,
phoneNumber: undefined
}
}, action) => {
switch (action.type) {
case SET_USER_CONTACT_INFO:
console.log(JSON.stringify(state));
state = {
...state,
authenticationObj: {
...state.authenticationObj, userContactInfo: action.payload.userContactInfo
}
};
console.log(JSON.stringify(state));
console.log(action.payload.userContactInfo);
}
return state;
};
export default AuthenticationReducer;
Before SET_USER_CONTACT_INFO call the state is as follows:
{
"authenticationObj": {
"isAuthenticating": false,
"isAuthentic": true,
"subscriberId": 4424,
"username": "cccc",
"firstName": "null",
"lastName": "null",
"email": "cccc",
"isAuthorized": true
},
"userContactInfo": {}
}
As you see "userContactInfo": {} is empty object which make sense now as soon as SET_USER_CONTACT_INFO request is dispatched I get:
{
"authenticationObj": {
"isAuthenticating": false,
"isAuthentic": true,
"subscriberId": 4424,
"username": "vvvv",
"firstName": "null",
"lastName": "null",
"email": "vvv",
"isAuthorized": true,
"userContactInfo": {
"country": "Canada",
"address1": "ssss",
"address2": "sss",
"city": "ssss",
"postalCode": "ss",
"phoneNumber": "sss"
}
},
"userContactInfo": {}
}
I get both userContactInfo one empty and one with info. It is really strange I expect the userContactInfo with new info is replaced with the empty one. what is wrong with my code? any help?
I expect the userContactInfo with new info is replaced with the empty one.
The two userContactInfo are on different levels. One is at the top level, next to authenticationObj, the other is in the value of authenticationObj itself, which you easily see by looking at the indentation. Besides, an object cannot have two properties with the same name.
{
"authenticationObj": {
"isAuthenticating": false,
"isAuthentic": true,
"subscriberId": 4424,
"username": "vvvv",
"firstName": "null",
"lastName": "null",
"email": "vvv",
"isAuthorized": true,
"userContactInfo": { // <root>.authenticationObj.userContactInfo
"country": "Canada",
"address1": "ssss",
"address2": "sss",
"city": "ssss",
"postalCode": "ss",
"phoneNumber": "sss"
}
},
"userContactInfo": {} // <root>.userContactInfo
}
I.e. you are merging the object on the wrong level. Seems what you want is
state = {
...state,
userContactInfo: action.payload.userContactInfo
};
This:
state = {
...state,
authenticationObj: {
...state.authenticationObj,
userContactInfo: action.payload.userContactInfo
}
};
Should be:
state = {
...state,
userContactInfo: {
...state.userContactInfo
action.payload.userContactInfo
}
};
You have told the script to insert the action.payload.userContactInfo into the authenticationObj, whereas it should placed as a sibling to it.
Sorry it's short I've wrote this on my phone.

Resources