Trying to trigger my alert box from my html depending if I get an “error 404” JSON response

I have been trying to get my alert box from my html to show up depending on the response I get in the console once I run the program, but I dont seem to get it working. Can anyone help me on this matter?

HTML:

        <div id="faultymsg" class="collapse alert alert-danger" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            <span class="sr-only">Close</span>
          </button>
          <strong>ERROR!</strong> We dont know that variable
        </div>
        </form>
        <div id="preloader" class="mt-5">
          <div class="spinner-border text-warning"></div>
        </div>  
        <div id="content" class="d-none">

What I have been trying in my javascript:

    } else if (response.status == 404 || response.statusText == 'Not Found') {
      document.getElementById('faultymsg').classList.remove('collapse');
        document.getElementById('faultymsg').classList.add('show');
  }
}

I am a beginner at JS so please be patient with me, thank you for any assistance!

How to verify user based on reCAPTCHA user response and secret key in react.js?

When reading the documentation, the following methods of verifying the user are shown:
For web users, you can get the user’s response token in one of three ways:

g-recaptcha-response POST parameter when the user submits the form on your site

grecaptcha.getResponse(opt_widget_id) after the user completes the reCAPTCHA challenge

As a string argument to your callback function if data-callback is specified in either the g-recaptcha tag attribute or the callback parameter in the grecaptcha.render method

How would I do any of those three in react.js, given that I have a token and the secret key?

When visiting the url from which the json is to be gathered, the following is found:

{
success: true,
score: 0.9,
domain: localhost,
}

How would I get the score in this case?

I have tried the following:

const response = await fetch(url);
var data = await response.json();

This produces a typeerror however, (failed to fetch).

How can I pull a large amount of data from a json object

I have a React application, the problem is that when I try to extract data from an already connected json file, which has two arrays with tables, when I try to display the data, instead of output, I get a white page and gives a TypeError in the console, for example: “Uncaught TypeError: Cannot access property ‘Table1’, no tables defined”

   const [tables,setTables] = React.useState()

  React.useEffect(() => {
    const date = setTimeout(() => {
        try{
          fetch('http://178.21.11.175/table-2017-01-01.json')
          .then(response => response.json())
          .then(json => {
            setTables(json)
          })
        }
        catch(err){
          console.warn(err);
        }
    },2000)
  },[tables])

Here I am extracting data from the json of the object

<td className="tg-0pky">{tables.Table1.name}</td>

The data itself is on this host: http://178.21.11.175/table-2017-01-01.json

Unauthorized Error when I want to delete article with authentification (jwt)

I’ve created a route called login and another one function(middleware), if the authentication is good, this can be redirected to the delete route but unfortunately, my jwt token is not recognizable.

I want to know why, the problem must be in this part of api :

Api


  function parseArticle (req, res, next) {



let token = req.headers['x-access-token'] || req.headers['authorization'];
if (!!token && token.startsWith('Bearer ')) {
  token = token.slice(7, token.length);
}

if (token) {
  jwt.verify(token, 'RANDOM_TOKEN_SECRET', (err, decoded) => {
    if (err) {
      return res.status(401).json('token_not_valid');
    } else {
      req.decoded = decoded;

      const expiresIn = 24 * 60 * 60;
      const newToken  = jwt.sign({
            user : decoded.user
          },
          'RANDOM_TOKEN_SECRET',
          {
            expiresIn: expiresIn
          });


      next();
    }
  });
} else {
  return res.status(401).json('token_required');
}



}

router.route('/article/:articleId')

.get(parseArticle, (req, res) => {
  
  db.query("SELECT *  FROM articles WHERE id_article = (?)", [req.articleId], function (err,result) { if (err) throw err;
    console.log(result);
    res.json(result)
  })

})


.put(parseArticle, (req, res) => {
  const name = req.body.name
  const description = req.body.description
  const image = req.body.image
  const price = parseInt(req.body.price)

  req.article.name = name
  req.article.description = description
  req.article.image = image
  req.article.price = price
  res.send()
})

.delete(parseArticle, (req, res) => {

  db.query("DELETE FROM articles WHERE id_article = (?)", [req.articleId], function (err,result) { if (err) throw err;
    console.log(result);})

res.json({message: "Propre"})})

router.post('/login', (req, res) => {
function runQuery(sqlQuery, args){
  return new Promise(function (resolve, reject) {
    db.query(sqlQuery, args, function(error, results, fields) {
      if (error) reject(error);
      else resolve(results);
    });
  });
}

runQuery("SELECT * from users where email = ? ", [req.body.email]).then(user => {
  if (user.length === 0) {
    return res.status(401).json({ error: 'Utilisateur non trouvé !',
      success : 0});
  }
  bcrypt.compare(req.body.password, user[0].password)
      .then(valid => {
        if (!valid) {
          return res.status(401).json({ error: 'Mot de passe incorrect !',
            success : 0});
        }


        const userId = user[0].id_user;
        const token = jwt.sign({ userId: user[0].id_user },
            'RANDOM_TOKEN_SECRET',
            { expiresIn: '24h' });
        res.header("Authorization","Bearer " + token)

        return res.status(200).json({success : 1})
      })

      .catch(error => res.status(500).json({ error }));

})
    .catch(error => res.status(500).json({ error }));
});

Login.vue

<template>

<form @submit.prevent="checkData">
  <input type="text" name="email" v-model="login.email" placeholder="Entrez votre adresse-mail"/>
  <input type="text" name="password" v-model="login.password" placeholder="Entrez votre mot de passe"/>
  <button type="submit"> Connexion </button>
</form>

</template>

<script>

module.exports = {
  name: "Login",

  data () {
    return {
      login : {
        email: "",
        password: "",
      },
    }
  },

  methods : {
     async checkData() {
       let user = {email : this.login.email, password : this.login.password}

      try {
        const response = await axios.post('/api/login', user)
        console.log(response.data.success)
        if(response.data.success === 1){
          await this.$router.push({name: 'home'})
        }
        if(response.data.success === 0){
          this.error = "Connexion Échouée"
        }

      }
      catch(err) {console.error("network error",err)}
    }
  }
}


</script>

<style scoped>
button {
  padding: 10px;
}
</style>

Thanks for you help,

Have a nice week-end

Using functions from imported modules in another file

Say I have file1.js and file2.js…

file1.js:

import React from 'react';

const test = ( {prop} ) => {
    function test1() {
        prop('1');
    }
    function test2() {
        prop('2');
    }
    function test3() {
        prop('3');
    }


    return (
        <div>
        ...          
        </div>
    )
}

export default test;

file2.js:

import test from './file1.js'

...

return (
   <button onClick={...}>
   </button>
)

...

How do I call any of the test1/2/3 functions with the onClick attribute in file2.js? Is that even possible? I am new to JS, so any and all feedback would be greatly appreciated!

Chrome extension message sending from background to content issue

I’m trying to send the current active URL from any updated tab to it’s respective content script with the code below. I’m having trouble confirming receipt of any message in the content script/page console. However, the console.log’s in the background.js are coming up.. I’ve also noticed that sometimes the changeInfo.url will send as undefined?

I’m new to Chrome extension development, what am I missing? Thanks!

background.js :

chrome.tabs.onUpdated.addListener( 
    function(tabId, changeInfo, tab) {
    if (changeInfo.url) {
        console.log(tabId, changeInfo.url, tab);
        chrome.tabs.sendMessage( tabId, {
            message: 'hello!',
            url: changeInfo.url
        })
    }
});

content.js :

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log("this is the url:" + request.url)
    }
)

Redux Toolkit: How can I store a serialized action creator in state?

Question

I am using Redux Toolkit and I want to store an action creator in state. When I do this, I receive an error regarding non-serializable values in my action as well as my state. Using the code below as an example of my issue, how can I resolve it without just suppressing the warning?

Slice Code

import { ActionCreatorWithoutPayload } from '@reduxjs/toolkit';

export type ModalType =
  {
    type: 'MyModal';
    actionText: string;
    onConfirm: ActionCreatorWithoutPayload;
  }

type ui = {
  modal: ModalType | null;
};

const initialState: ui = {
  modal: null
};

export const slice = createSlice({
  name: 'ui',
  initialState: initialState,
  reducers: {
    showDialog: (state, action: PayloadAction<ModalType>) => {
      state.modal= action.payload;
    },
    someAction: (state) => {
      // do something
    },
  }
});

Component Code

import { someAction } from 'reducers/uiSlice';

<Button
  onClick={() =>
  dispatch(
    showDialog({
      type: 'MyModal', actionText: `Some text`, onConfirm: someAction}
    )
  )}
/>

Error Message

A non-serializable value was detected in an action, in the state: `payload.onConfirm`. Value: ƒ actionCreator() {
    var args = [];

    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }

    if (prepareAction) {
      var prepared = prepareAction.apply(void… 

check number equality in Javascript

I have numbers that will be coming from database with this format “+2349091736209” and I want to compare each number with a number I get from user contacts list. The value of phone numbers I get from the contacts is sometimes in this format “0909 173 6209” with spaces, while sometime like this “0909-173-6209”. I need help on how to compare the db value with this variants and get if its a match. Thanks.

How to set setUserProperty

To set the value for the user ID, set the value with setUserID and set the value.
To get the value of the user ID also in the user property
You also need to set the value of ”customer_id(Our service ID)” in setUserProperty.

I read the article below 
https://firebase.google.com/docs/analytics/user-properties?platform=ios

Based on the following document, so that you can set setUserProperty from WebView
I am preparing the interface on the native side, but it is not GTM,
Is it okay to understand that you set the setUserProperty natively?
https://firebase.google.com/docs/analytics/webview?hl=ja&platform=ios

I don’t call it by the natives themselves,
If it is called via WebView, it will work.

Is my understanding correct?

Schema for saving a lot of questions MongoDb

  1. If I have a survey application for child tracking what is the best way to save survey questions in MongoDB?
    Knowing that survey is divided into stages (about 12 stages), each stage is divided into 4 categories and each category has a number of questions.
    In other words, what is the best schema model to save such a date contains a lot of questions?
 const devCheckListSchema = new mongoose.Schema({
      childName: {
        type: String,
        trim: true,
        required: [true, 'Name is required!']
      },
      createdAt: {
        type: Date,
        default: Date.now
      },
      // ...
    });
  1. Questions are in the Arabic language is there any way to store them in mongodb datebase them in Arabic?

array.slice strange behaviour with nuxt-edge

I was previously using nuxt 2.xx and since switching to nuxt-edge the vue behavior changed with array.slice. Let me explain :

My code is very basic and is used to add/remove items of an array in a child component “stockLiens”. This array is passed to a parent component “currentEtabCommentUser” via .sync

Everything was working fine before but since I’m with nuxt-edge, if I have – for instance – an array of 3 items and I want to delete the 2nd one, it is the only item left!

My stockLiens component Javascript is the following:

props: {
    liens: {
      type: Array,
      default: () => []
    }
},
methods: {
    // I used concat() and slice() to avoid mutating a prop in the component
    add () {
      const arrayConcat = this.liens.concat([{ url: '', description: '' }])
      this.$emit('update:liens', arrayConcat)
    },
    remove (index) {
      const arrayCopy = this.liens.slice()
      console.log(this.liens) // line 108
      console.log(arrayCopy) // line 109
      this.$emit('update:liens', arrayCopy.splice(index, 1))
      console.log(arrayCopy) // line 111
    }
}

When I run the script, the text in the firefox console is the following:
I’m not allowed to publish picture yet so it’s a link
On the picture, you can see that :

  • stockLiens:108 is an array of 3 items (it makes sense since it is this.liens)
  • stockLiens:109 is an array of 2 items! (strange since it’s a simple array.slice() of this.liens) The 2 items are the old index 0 and the old index 2 (I’ve clicked on old index 1)
  • stockLiens:111 is the same array that on line 109. (strange again because it should have been spliced in line 110)
  • currentEtabCommentUser:186 is an array of 1 item : the old index 1 (since line 186 is just a listener on this.liens, it should be the same array that on stockLiens:111. I really don’t understand anything!)

My currentEtabCommentUsercomponent:

<stockLiens
   :liens.sync="liens"
/>

<script>
  watch: {
    liens () {
      console.log(this.liens) // line 186
    }
  }
</script>

I’ve tried to change .sync, to copy the array with for(i…), to get() / set(v) the liens property, … I’ve looked on many forum during hours (2 days now) but I can’t understand the problem.

Can someone help me please ?
Thank you in advance!

My stockLiens component HTML:

<v-card
   v-for="(url, i) in liens"
  :key="i"
>
            <v-text-field
              v-model="url.url"
              label="Url"
            />
            <v-text-field
              v-model="url.description"
              label="Description"
            />
          <v-divider vertical />
          <v-btn
            icon
            @click="remove(i)"
          >
            <v-icon>mdi-delete-forever-outline</v-icon>
          </v-btn>
</v-card>

Infinite Automatic Horizontal Scroll With Static Content Underneath

I’m trying to create a horizontal bar of images at the top of my webpage. I’d like the banner of images to slowly pan-through/scroll automatically on page load, but I don’t want the entire page to scroll along with it because there’s content underneath the banner I want to stay in place for the viewer. Also I would like the banner to be infinite so when it gets to the end it seamlessly restarts. I’m thinking I can use setInterval and put the container div on overflow: scroll, but again I would like for the entire page to remain static. Any ideas are greatly appreciated.

[enter image description here][1]

import './CategoryList.scss'

export default function CategoryList({ categories }) {


  return (
    <div className="categories">
      <ul className="categories__list">
      {categories && categories.map((category, i) => {
          return (
            <div key={i} className="categories__card">
              <Link
                to={`/guides/${category.id}`}
                key={i}
                className="categories__link"
              >
                <h3 className="categories__title">{`${category.name}`}</h3>
                <img
                  className="categories__poster"
                  src={category.poster}
                  alt="guide cover"
                />
              </Link>
            </div>
          );
        })}
      </ul>
    </div>
  )
}


  [1]: https://i.stack.imgur.com/Uh7Mu.png

Trying to refactor React App to React-Redux issue w/ volume slider

I’ve been doing freecodecamps Drum Machine app. I was able to complete the app completely with React but I made a copy to try and get familiar with using react-redux together and I’m not doing something correct when trying to refactor the input slider. It will not change the volume of the clips and it does not update the display with the volume change.

This is my working react app
React Only Drum Machine

This is the one I’m trying to refactor
React-Redux Drum Machine

This is a guy that I patterned a lot of mine from trying to understand how to put into practice what I learned from freecodecamp
J8ahmed Drum Machine

I think it might be something about this code here but I’m not sure

<input type="range" min="0" max="1" step=".1" value={this.props.volume} className="slider" id="myRange" onChange={(e)=>{this.props.volumeToggle(e)}}/>

Create a ‘Customer’ Function [closed]

Develop a new JavaScript program with the following tasks.

Create a ‘Customer’ function and pass by value the following parameters: ‘fullname’ (string), ‘cellphone’ (string) and ‘email’ address (string). Call this function and print the passed parameters.

Implement setters and getters properties for a ‘Customer’ entity with ‘fullname’ (string), ‘cellphone’ (string) and ‘email’ address (string) data fields.

Demonstrate how to parse a JSON object. Create a Customer JSON object with ‘fullname’ (string), ‘cellphone’ (string) and ‘email’ address (string) data fields.