Using useState doesnt automatically set data?

I’m new to react so maybe I’m missing something but I’ve encountered something weird.

I have this useState

const [postsurl, setPostsurl] = useState([])

and then I fill it with data from a promise

setPostsurl(result.data)

When I console.log the result.data after this, it prints out the data just fine. However, when I console.log(postsurl) after setting it, it’s still an empty array. I’m assuming this has to do with the way the language works. Is there any way to resolve this?

Gradients on edges of swiper carousel

I want behavior like the one on this airbnb web page. Specifically, the one in the below image.
enter image description here
As you can see, at the edges of the carousel, it has a fading effect only on slide that are cut off.

This is what I have so far: https://jsfiddle.net/gpu5cafz/.

HTML (make sure to install Swiper if you aren’t using the jsfiddle):

<div class="container">
  <div class="swiper">
    <!-- Additional required wrapper -->
    <div class="swiper-wrapper">
      <!-- Slides -->
      <div class="swiper-slide">Slide 1</div>
      <div class="swiper-slide">Slide 2</div>
      <div class="swiper-slide">Slide 3</div>
      <div class="swiper-slide">Slide 4</div>
      <div class="swiper-slide">Slide 5</div>
    </div>
  </div>
</div>

CSS:

.swiper-slide {
  width: 300px !important;
  height: 200px !important;
  text-decoration: none;
  background-color: gray;
  border-radius: 10px;
  color: white;
  background: rgb(203, 203, 203);
}

.container {
  padding: 60px 120px 60px 120px;
}

JS:

const swiper = new Swiper('.swiper', {
  slidesPerView: 'auto',
  spaceBetween: 30,
  freeMode: true,
  freeModeSticky: false,
  watchSlidesProgress: true,
  watchSlidesVisibility: true,
});

Express DELETE 500 (Internal Server Error)

I’m trying to Remove my User from the system, but I’m getting error 500 (Internal Server Error)

I tried this with my Product and it still works fine. I didn’t know where did I go wrong?

Below is my code

Router

router.get('/user-list/remove/:user_id', adminController.removeUser);

Service

async removeUser(user_id) {
    const userInDb = await this.userRepository.getById(user_id);
    if (userInDb) {
        await userInDb.destroy();
    } else {
        throw new Error();
    }
}

Controller

const removeUser = async (req, res) => {
try {
    const adminService = new AdminService();
    const data = req.params.user_id;
    await adminService.removeUser(data);
    res.send();
} catch (error) {
    res.status(500).json({ TRAVE: true, message: error });
}}

EJS

<a>
    <button class="deletebutton" value="<%= users[i].user_id %>">Delete</button>
</a>

<script type="text/javascript">
            $('.deletebutton').on("click", function (event) {
                event.preventDefault();
                var user_id = $(this).val();
                if (confirm("Are you sure you want to delete this data?")) {
                    $.ajax({
                        url: `/admin/user-list/remove/${user_id}`,
                        method: 'get',
                        data: { user_id: user_id },
                        success: function (data, textStatus, xhr) {
                            if (xhr.status == 200 || xhr.status == '200') {
                                $('.notification').html(`Delete done!`)
                            } else {
                                alert('Some error occurred try again');
                            }
                        },
                        error: function (response) {
                            error.html(`${response.responseJSON.message}`);
                        }
                    });
                }
            });
        </script>

And this is what I get from Console.log

GET http://localhost:5000/admin/user-list/remove/2?user_id=2 500 (Internal Server Error)

I tried with router.delete and method: 'delete' in the script but I get the same result. Where have I encountered the problem?
I have a Product table, I have user_id as a foreign key, is it a problem?

Selecting a “span” without clicking it

I have a code to highlight the sentence when I click it but I need to add one more thing also to be able to select a “span” without clicking it just when the reading continues from span to span.

let sentence = $('.sentence').text();

sentences = sentence.split('.')
$('.sentence').html('');

for (let s of sentences) {
  $('.sentence').append('<span>' + s + '.</span>')
}

$('.sentence span').on('click', function() {
  $(this).addClass('highlight').siblings().removeClass('highlight');
});
.sentence span:hover,
.highlight {
  background: Yellow;
}

 body {
            text-align: justify;
            text-justify: inter-word;
            background-color: #D9EAE6;
        }
        
        
        
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="sentence">
(1)Lorem ipsum dolor sit amet consectetur adipiscing elit.
(2)Pellentesque iaculis.
(3)Pellentesque iaculis nisl at erat dapibus cursus.
(4)Pellentesque iaculis.
(5)amet consectetur adipiscing elit.
(6)adipiscing elit.
</p>

Setting Error Messages Around the Applicable Form Elements in Loop

I have this function and I need error message to be applied on around particular element; where validation fails.

Currently the SetError message is applied all the form elements in the loop.

async function onUserInput(element, value) {
console.log(element);
if (typeof element === 'string') {
  let pageUserInputCopy = [...pageUserInput];
  let index = pageUserInputCopy.findIndex((obj) => obj.key === element);
  let itemCopy = { ...pageUserInputCopy[index] };

  itemCopy['userInput'] = value;
  pageUserInputCopy[index] = itemCopy;

  setPageUserInput(pageUserInputCopy);
}
if (await isValid(value)== false) {
  setErrorMessage('Collection Container ID already exists!');
  setHasError(true);
}

}

How to find a subelement of a node, which is not attached to the dom?

I use jquery and es6 template strings to create a checkbox with a label:

function createCheckBx(id, text) {
        return $(`<div>
                    <input id ="${id}" type="checkbox"/>
                    <label for="${id}">${text}</label>
                 </div>`);
}

Now I would like to attach an eventlistener to the checkbox

checkBox = createCheckBx("42", "Answer");
cb.???.addEventListener("change", (evt) => {
  // do smth. when toggled
})

but the div is not attached to the dom yet so I can’t use
use document.getElementById (or jquery’s $("#...") and I don’t want to access it by any kind of index like cb.childNodes[1], since the caller can’t know the index and html structure may change. Any help?

kindly regards, AJ

Custom Service not giving desired result in controller in AngularJS 1.8

I have to debug a snippet written in AngularJS.


//===== service ==
app.service('allUserService', function($http) {

    var config = {
        headers: {
            'X-XSRF-TOKEN': gettingValueFromSomewhere()
        }
    };


        this.getAll = function() {
            var restUrl = CONTEXT_PATH + '/rest/path/mypath';
            
             return $http.get(restUrl, config).then(function(response) {
            console.log(response.data.body); // console prints an Array which is correct
                return response.data.body;
            });
        }

});

//========= controller ====
app.controller('UserCtrl', function($scope,allUserService) {
            var valueArray = [];
            valueArray = allUserService.getAll();
            console.log(valueArray);
            $scope.faqBook = valueArray; 
          
         });

allUserService :I am getting correct result from Rest webservie and console log shows desired return (an Array)

faqUserCtrl : I am not getting desired value in console log. Pls help me in finding the issue. It should have an array. I am expecting an Array in $scope.faqBook

<div class="container" ng-app="UserModule" ng-controller="UserCtrl">

  <p>Search : <input type="text" ng-model="search"/></p>
    
<table id="mainTable" class="table table-striped table-hover">
  <tr ng-repeat="x in faqBook | filter:search">

    <td><ul class="list-group"><li class="list-group-item">Question: {{ x.question }}</li><li class="list-group-item"> Answer: {{ x.answer }}</li></ul></td>

  </tr>
</table> 
</div>

The skill is rejecting the request when executed with additional properties in the JSON request

I’m having problems when I deploy my alexa skill to google cloud functions.

Initially, I’m using the following code.

My skill.js file

//imports here...

  Router.post("/:locale", async (req, res) => {
    const requestEnvelope = JSON.stringify(req.body);
    try {
      await new SkillRequestSignatureVerifier().verify(requestEnvelope, req.headers);
      await new TimestampVerifier().verify(requestEnvelope);
    } catch (err) {
      console.log(`Error with message: ${err.message}`);
      console.log(`Error object: ${JSON.stringify(err)}`);
      return res.status(400).send(err.message);
    }
    const responseASK = await skill.invoke(req.body);
    return res.status(200).send(responseASK);
  });

module.exports = Router;

In my server.js file

const skillRoute = require("./skill");

const express = require("express");
const server = express();
server.use("/", skillRoute);

exports.server = functions.https.onRequest(server);

Everything goes well with the deploy, including, I can invoke my alexa skill normally. But, when running the validations for distribution, I get the following problem:


The skill is rejecting the request when executed with additional properties in the JSON request.

When we invoke the skill with additional parameters, the skill is rejecting it when we expect this to be accepted. Future versions of the Alexa Skills Kit may add new properties to the JSON request and response formats, while maintaining backward compatibility for the existing properties. Your code must be resilient to these types of changes. For example, your code for de-serializing a JSON request must not break when it encounters a new, unknown property. Please ensure that your code can handle new attributes and does not break when it encounters new properties in the JSON request.
Documentation Help:
Request and response JSON reference:
Click here


On my server console I get the following errors:

Error with message: request body and signature does not match

and:

Error object: {"name":"AskSdk.SkillRequestSignatureVerifier Error"}

It seems to me that it may be the result of some ask-sdk-core update, as I have other servers working with the same code.

javascrpit not working with aria-label show empty

<button type="button" class="plyr__control" data-plyr="play" aria-label="Play">

After click button

<button type="button" class="plyr__control plyr__control--pressed" data-plyr="play" aria-label="Pause">

my scrpit

<script>
const $featured = $('.plyr__control');

// bind a change event handler to the input
$featured.on('change', function() {
    if (button.getAttribute('aria-label') === 'Pause') {
console.log('ok');

    }
});
</script>

here JavaScript not working.how to solve this

Why am I keeping getting ‘Collection is undefined’ error on MongoDb

I tried to connect to my db but it keep on returning that the collection is undefined even though I already declared it as a global variable. Not really sure what the closure issue is.

const express = require('express');

const app = express(); 

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let db;
MongoClient.connect('mongodb://localhost:27017/todos', { useUnifiedTopology: true },  (err, client) => {
  assert.equal(nul, err);

  db = client.db('todos'); 
  db.collection('todos').insertMany([
    { done:true, desc: 'write code'},
    { done:true, desc: 'write code'},
    { done:true, desc: 'write code'},
  ]);
  client.close();
})


app.get('/', (req, res) => {
    res.json('did this work!');
}); 


app.get('/todos', async (req, res) => {
    const todos = await db.collection('todos').find().toArray();
    res.json(todos);
  });
  
app.listen(3001, () =>{
    console.log("work pls");
}); 

Autoplay in slider with js

let left = document.querySelector('.left');
let right = document.querySelector('.right');
let img = document.querySelector('.imgs');
let imgs = document.querySelectorAll('img');

let index = 0;


function rightimg() {
  right.addEventListener('click', function () {
    index++;
    if (index > imgs.length - 1) {
      index = 0;
    }
    img.style.transform = `translateX(${-index * 500}px)`;
    console.log(img);
  });
}

// setInterval(rightimg, 2000);

left.addEventListener('click', function () {
  index--;
  if (index < 0) {
    index = imgs.length - 1;
  }
  img.style.transform = `translateX(${-index * 500}px)`;
  console.log(img);
});

Hi friends,
I want to make autoplay image in this slider but setInterval is not working,
can you say what is wrong in here?
Thank you

Express/axios don’t set cookies and headers for response

I have very complicated problem. My project has 2 API’s. 1 API is for front-end of my application and 1 is for back-end. How it works, is just I send request from front-end API to back-end API.

Front-end API has URL http://localhost:8080/api/ and back-end API has URL http://localhost:3000.

The problem is front-end API can’t get cookies from back-end API.

Here is example, function of front-end API just send request to back-end:

router.get('/test-front-api', async (req, res) => {
  const data = await api.get('/test-back-api')
  return res.json(data.data)
})

Back-and just sends cookie and some random text:

router.get("/test-back-api", (req, res) => {
  res.cookie("test", "cookie")
  res.send("Hi from back-end")
})

A here is where I have problem:

router.get('/test-front-api', async (req, res) => {
  const data = await api.get('/test-back-api')
  console.log(data.headers) // If you do console.log here you will this cookie test
  return res.json(data.data)
})

But this cookie is not set in browser.

Let me show one more example. In browser I can just type http://localhost:8080/api/test-front-api and here is result, no cookie:

enter image description here

But, if I type not front-end API endpoint, but back-end, everything works perfect:

enter image description here

I was trying literally everything I found about cors options, axios {withCredentials: true} etc. Nothing works.

I have found one solution, but I don’t like it:

router.get('/test-front-api', async (req, res) => {
  const data = await api.get('/test-back-api')
  // Something like this
  res.cookie("test", JSON.stringify(data.headers['set-cookie']))
  return res.json(data.data)
})

So, my question is why cookie is no set by front-end endpoint?

CSS not working inside subfolder in reactjs

I am working in Reactjs and i am using “Nextjs” framework,I am working in project
Where i put my “Head” (include css ) code in “document.js”,Everything is working fine but whenever
i open “blog detail” page which exist in “subfolder”(“pages/fr”) then “css” not working after page refresh, in other words “css” is not working after “page refresh” in “blg_detail” section
How can i fix this, Here is my current “_document.js” code

import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'

export default function Document() {
  return (
    <Html>
      <Head>
                <link
                  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
                  rel="stylesheet"
                  integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
                  crossOrigin="anonymous"
                />
                <link rel="stylesheet" type="text/css" href="css/style.css" />
                <link rel="stylesheet" type="text/css" href="css/responsive.css" />

                <link
                  href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400;500;600;700&family=Darker+Grotesque:wght@300;400&family=Poppins:wght@100;300;400;500;700&display=swap"
                  rel="stylesheet"
                />
      </Head>
      <body>
        <Main />
        <NextScript />

  
      </body>
    </Html>
  )
}