Props value based on a stored cookie - reactjs

Based on a specific value from a stored cookie (selectedRetailerId) the source (API endpoint) is different.
I'm trying to store the value of the cookie in a variable called retailer_id and use that to make sure the correct endpoint is called.
Here's what I'm trying...
<OTHER CODE IS REDACTED>
ReactDOM.render(
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var retailer_id = getCookie(selectedRetailerId);
<DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
document.getElementById('deliveryOptionsContainer')
)
But this returns a Uncaught SyntaxError. Probably because this piece of code should not be in ReactDOM.render.
Uncaught SyntaxError: http://localhost:8000/src/app.js: Unexpected token (130:2)
128 | }
129 |
> 130 | var retailer_id = getCookie(selectedRetailerId);
| ^
131 |
132 | <DeliveryOptionsTable source="http://<REDACTED>/delivery_options/{retailer_id}" />,
133 | document.getElementById('deliveryOptionsContainer')
What is the right way to do this with React?

Try this:
// Defined somewhere outside ReactDOM.render (I'd recommend a helpers.js file)
// If you move it out of this file, be sure to import / require it
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
ReactDOM.render(
<DeliveryOptionsTable source={"http://<REDACTED>/delivery_options/" + getCookie(selectedRetailerId)} />,
document.getElementById('deliveryOptionsContainer')
)

Related

if the command used does not contain a valid hex code

if (command === "hex")
{ let hex = args[0]
if(!hex) return message.reply("Please specify a hex code!")
function hexToRgb(hex) {
if (hex.charAt(0) === '#') hex = hex.substring(1)
if(!hexToRgb(hex)) return message.reply("Not a valid hex.")
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
let embed = new Discord.MessageEmbed()
.setTitle("Hex Code")
.setColor(hex)
.addFields(
{
name: `RGB`,
value: hexToRgb(hex) + ``
}
)
message.channel.send({embeds: [embed]})
}
Here is my above code for the hex command. I would like the bot to send a message that it's unable to convert hex to color if the user is using an invalid hex code (e.g. #GGGGGG) or a non-hex code (e.g. "Hello"). How could I achieve that?
You can use regex. This simple function will return whether or not it is a valid hex code
String.prototype.isHex = function() {
return ( this.match(/#?[a-f0-9]+/i)?.[0] || false )
}
And run it like this
'#ffffff'.isHex() //'#ffffff'
'Hello'.isHex() //false
'#gggggg'.isHex() //false
You can use a RegExp (#[A-Za-z0-9_]{6}) to validate the string as a hexadecimal value preceded by a #
function isHex(str) {
return !!str.match(/#[A-Za-z0-9_]{6}/).length;
}
if (!isHex('some value')) return message.reply("Not a valid hex.")

How to replace Pipelet for ExportCustomerGroups in SFCC? (For removing Deprecated API usage)

function abc(){
var Site = require('dw/system/Site');
var utils= require('app_nars/cartridge/scripts/util/utils.js');
var mySite : String = (Site.getCurrent().getID() == "a") ? "" : "-" + Site.getCurrent().getID();
var customerGroupName : String ;
if (mySite == "A") {
customerGroupName = "A";
} else {
customerGroupName = "B";
}
var grpNam= utils.getGroup(customerGroupName);
var grpFileName = 'test';
/* No script api available for pipelet ExportCustomerGroups*/
var Pipelet = require('dw/system/Pipelet');
var PipeletExecutionResponse = new dw.system.Pipelet('ExportCustomerGroups').execute({
CustomerGroups: grpNam.iterator(),
ExportFile : grpFileName,
OverwriteExportFile:true
});
app.getView().render('path/templateName');
}
How can we replace the Pipelet ExportCustomerGroups here , i could see in documentation we can use job steps and there is no script replacement
You have to create with your own code, construct the xml needed while parsing the customers.[enter image description here][1]
Or you can use this step when configuring job if no custom code needed there:
[1]: https://i.stack.imgur.com/s1VQa.png

React Amplify/Datastore- cannot get delete record to delete

In react, I have the following code which is running offline. I obviously found it.:
async function deleteMessage() {
toDelete = await DataStore.query(Message, c => c.id("eq","4faebf3b-f89a-4e34-978a-0fea611897e0"))
alert("toDelete: " + !toDelete ? toDelete : toDelete.length )
if (!toDelete || (toDelete !== undefined && toDelete.length == 0))
{
alert("Nothing to delete")
return
}
alert("Deleting " + toDelete.length + " records.")
alert("id for 0 = " + toDelete[0].id + " title: " + toDelete[0].title + " color: " + toDelete[0].color + " createdAt: " + toDelete[0].createdAt)
await DataStore.delete(toDelete);
alert("after delete")
// updateFormState(initialState)
}
toDelete has all the fields correct and is being displayed in the alert before the actual delete, so toDelete should be the correct model.
The one alert is saying: Deleting 1 records.
The next alert says: id for 0 = 4faebf3b-f89a-4e34-978a-0fea611897e0 title: aaasdfasdf color: #6c2f2f createdAt: undefined
But it never returns from the delete and I am getting the error:
Unhandled Rejection (Error): Object is not an instance of a valid model
DataStore.<anonymous>
C:/Projects/React/src/datastore/datastore.ts:897
894 | sortPredicate = ModelSortPredicateCreator.createFromExisting(modelDefinition, paginationProducer.sort);
895 | }
896 | return {
> 897 | limit: limit,
| ^ 898 | page: page,
899 | sort: sortPredicate,
900 | };
View compiled
What am I missing?
Also, the model is:
type Message #model {
id: ID!
title: String!
color: String
createdAt: String
}
Thanks.
Figured it out.
Change toDelete = await DataStore.query(Message, c => c.id("eq","4faebf3b-f89a-4e34-978a-0fea611897e0"))
to
toDelete = await DataStore.query(Message, "4faebf3b-f89a-4e34-978a-0fea611897e0"))
The first example returns an array of objects.
The second example returns an object.
The DataStore.delete() expects an object not an array of objects. I was passing an array of objects.
DataStore.delete(toDelete) would work with the 2nd example but not the first since that was an object.
If I am using the first example would have to use:
DataStore.delete(toDelete[0])

Convert objectGuid to UUID string using Javascript

I have been looking for a way to convert the ObjectGuid out of Active Directory is a special type that gets converted to a string, which is odd looking, using libraries such as ldapjs and or adding it as a claim using ping federate. An example of this is the following:
const ldapjs = require("ldapjs");
let _client = ldapjs.createClient({
"url": this._ldap_uri
});
_client.search(this._search_dn, opts, (error, res) => {
res.on("searchEntry", (entry) => {
console.log(entry.object.objectGUID)
}
Here is an example of the output that comes out of ldapjs. The same comes out of a ping federate when you add it as a claim.
H�Y��fB�_-_���
However, this is equivalent to a valid UUID.
b9****48-6***-42**-a**f-2d5f*****40b
What I am trying to do is convert this strange value to a the correct UUID. I have scoured and tested a few different postings and websites but I have not found a valid solution.
Here are a few I researched:
Read objectGUID from active directory
Javascript convert GUID in string format into Base64
http://www.tdi-users.org/foswiki/Integrator/UsingGUIDs
If anyone has a solution to this it would be appreciated.
experiment with this code (read GUID) :
String.prototype.padLeft = function( len, str ) {
//return Array( len - String(this).length + 1 ).join(str) + this;
var s = this;
str = str || '0';
if ( str.length > 0 ) {
while ( s.length < len ) {
s = ( str + s );
};
}
return s;
}
var destAD = GetObject("LDAP://dc.yourdomain.pl/cn=Administrator,cn=Users,dc=yourdomain,dc=pl");
var guidValueArr = destAD.Get("objectguid").toArray();
var guid = "", i;
for ( i = 0; i < guidValueArr.length; i ++ ) {
guid += guidValueArr[i].toString(16).padLeft(2,"0");
}
var guidFormated = guid.replace(/(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.{4})(.{12})/, "$4$3$2$1-$6$5-$8$7-$9-$10");
alert( guidFormated );
Universally unique identifier

extracting Array data from SharedObject

Im having a game where after I finish a certain level I put that level`s name In an Array and save that array to an SharedObject(SO). But somehow/somewhere I mess up things, because after closing and opening the game again, I load the SO data (to unlock the levels that I have passed) and it is (the loaded data) always messed up and not loading what it should load(sometimes it even trows some errors at me.)
The code is not that difficult but I have been looking at it for far to long and I need new eyes to see the obvious mistakes in it.
***********EDIT**********
So the code for the SO is this
public class LevelsData extends SharedObject
{
public static var LEVELS_DATA:SharedObject = SharedObject.getLocal("save_poi71");
public static function get LoadNamesOfLevelPassed():Array
{
var myLevelsArr:Array = [];
if( LEVELS_DATA.data.PlayedLevels_arr == undefined)
{
myLevelsArr.length = 0;
}
else
{
myLevelsArr = LEVELS_DATA.data.PlayedLevels_arr;
}
return myLevelsArr;
}
public static function set SaveLevel_Names( nameOfLevelPassed:Array ):void
{
LEVELS_DATA.data.PlayedLevels_arr = nameOfLevelPassed;
LEVELS_DATA.flush();
}
}
and the code in the game is this
.
.
.
.
private function didWePlaySameLevel():void
{
var namesPlayed_arr:Array = LevelsData.LoadNamesOfLevelPassed;
var namesTotal:int = namesPlayed_arr.length;
if( namesTotal == 0 )
{
trace(" ScreenInGame_2 | didWePlaySameLevel | namesTotal == 0 so we push Level_1");
namesPlayed_arr.push( Moving_Picture_Name );
LevelsData.SaveLevel_Names = namesPlayed_arr;
sameLevel = false;
}
else if( namesTotal != 0 )
{
for( var i:int = 0; i < namesTotal; i++)
{
trace(" ScreenInGame_2 | didWePlaySameLevel | " + Moving_Picture_Name + " ?==? " + namesPlayed_arr[ i ] );
trace(" ScreenInGame_2 | didWePlaySameLevel | namesPlayed_arr.length = " + namesPlayed_arr.length);
if( Moving_Picture_Name != namesPlayed_arr[ i ] )
{
trace(" ScreenInGame_2 | didWePlaySameLevel | " + Moving_Picture_Name + " != " + namesPlayed_arr[ i ] );
namesPlayed_arr.push( Moving_Picture_Name );
LevelsData.SaveLevel_Names = namesPlayed_arr;
sameLevel = false;
trace(" ScreenInGame_2 | didWePlaySameLevel | namesPlayed_arr.length = " + namesPlayed_arr.length);
}
}
}
}
.
.
.
if( levelsToUnlock < totalLevels && sameLevel == false )
{
trace("ScreenInGame | unlockOneMoreLevel | we UNLOCK 1 more level" );
unlockNextLevel();
}
***EDIT PROBLEM:
SomeHow i figured a way of solving my 1st problem, but now there is a new one and that is :
When the Array from the SO is != 0 i go into the else if statement. There i compare if any of the variables in the Array have the same name of the Moving_Picture_Name and if they dont then I set the sameLevel = false. The problem is that, if lets say I have passed/played 5 levels before( Level_1,Level_2,Level_3,Level_4,Level_5 ) and lets say I start playing Level_2 again it would show me this:
Level_2 != Level_1 - > and it will push itself into the Array and update the data
Level_2 == Level_2 - > it will do nothing
Level_2 != Level_3 - > and it will push itself into the Array and update the data
Level_2 != Level_4 - > and it will push itself into the Array and update the data
Level_2 != Level_5 - > and it will push itself into the Array and update the data
so it will actually push 4 Elements in the Array that exist already in that Array.
***THE QUESTION :
So how do I push the newLevel only if its name isnt in that Array(the one where I save the names), And how do I do nothing if the name exist in the Array already.
You may have to convert your array to ByteArray, and save that. When you read it back, you will have to do the reverse operation. StackOverflow example link

Resources