How to render a list of array items depending on the selected calendar item in a Vue project?

Here’s the calendar I’m talking about:

CalendarApp

So, basically, I’ve tried to create a following feature: Each day item contains an empty array which will then contain the N number of tasks that are added to that empty array by the purple button below depending on which day is active (The highlighted one), so each day item will have its own array of tasks and I can switch between them to see how many tasks on which day are created. I use Vuex and Vue3 Composition API for this project.

Calendar component:

Calendar.vue

<template>
<div class="wrapper">
  <div class="calendar-wrapper">
      <div class="calendar-row"
           v-for="(day, idx) in dayArr"
           :key="idx"
        >
          <div
            id="card"
            class="day-card "
            :class="{ 'active' : activeDay === idx + 1 }"
            @click="switchDay(idx)"
          > 
              <div class="card-info">
                <p class="name">{{ day.dayOfWeek }}</p>
                <p class="day">
                    {{ day.currDay }} 
                </p>
              </div>
             <div class="dot-wrapper">
                <div class="dot-status undone" />
                <div class="dot-status undone" />
             </div>
          </div>

      </div>
  </div>
</div>
</template>

<script>
/* eslint-disable no-unused-vars */
import { useStore } from 'vuex'
import { onMounted, ref } from 'vue'

export default {
  
  /*=============================================
  =            Setup            =
  =============================================*/
    setup() {
    // ? Turn the remaining days into an array 
    const fillDayArray = () => {
      dayArr.value = Array(daysRemainingThisMonth)
        .fill('')
        .map((item, index) => {
          return {
            currDay: moment().add(index, 'day').format('D'),
            dayOfWeek: moment().add(index, 'day').format('dddd'),

            // Empty array for added tasks:
            tasks: []
  
          };

      })

      }
     // Make the clicked day active
    const switchDay = (idx) =>  {
      activeDay.value = idx + 1
    }

    onMounted(() => {
      fillDayArray() 
      
    })

</script>

Area where tasks are rendered and created:

TaskView.vue

<template>
    <div class="task-wrapper">
        <p id="task-counter">
            Tasks Today: {{ taskArr.length }}
        </p>
        <div class="task-counter-wrapper">                 
            <!-- ? Render if there are no tasks available: -->
            <div 
                class="empty-msg"
                v-if="taskArr.length == 0"
            >
                <p>Start by adding a New Task!</p>
            </div>

            <div 
                class="task-list" 
                v-for="(task, idx) in taskArr"
                :key="idx"
            >
                <div class="list-item">
                    <div class="container">
                        <input class="list-checkbox" type="checkbox">
                        ({{ idx + 1}}) {{ task.name }}
                    </div>

                    <div class="item-actions">
                        <button 
                            class="edit-item btn"
                            @click="getClickedTask(task)"
                        > 
                            <img class="icon" src="./Images/editing.png">
                        </button>

                        <button 
                            class="delete-item btn"
                            @click="deleteItem(idx)"
                        >
                            <img class="icon" src="./Images/delete.png">
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="item-card">
            <ItemCard />
        </div>  

        <div class="add-task-wrapper">
            <button 
                id="add-task-btn"
                @click="addItem()"
            >
                + Add a new task
            </button>
        </div>
    
    </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
import ItemCard from './ItemCard.vue'
import { useStore } from 'vuex'
// import { computed } from '@vue/reactivity'

export default {
    components: {
        ItemCard
    },

    setup() {
        const store = useStore()
        const taskArr = store.state.taskArr
    
    
        const getClickedTask = (item) => {
            store.state.clickedTask = item
            
            store.state.cardStatus ?
                store.state.cardStatus = false 
                :
                store.state.cardStatus = true
        };

        // ! Delete Item:
        const deleteItem = (idx) => {
            store.state.taskArr.splice(idx, 1)
        }

        const addItem = () => {
            store.state.taskArr.push(
                {
                    name: 'Empty Task' + Math.random().toString().substring(0, 4), 
                    description: 'No description...' 
                }
            )
        }
            
    },

}
</script>

Main area where all other component are rendered:

Main.vue

<template>
 <div id="main">
     <!-- ! Top Level: -->
    <div class="auth">
        
    </div>
    
    <div class="greeting-block">
         <button @click="signOutUser">Sign Out</button>
         <h1 id="greet-user"> {{ user?.email }}</h1>
    </div>

     <div class="header-container">
         <Header />
         <Menu />
         
     </div>

    <div class="calendar-display">
        <Calendar />
    </div>

 
    <div class="task-list">
        <TaskView />
    </div>

 </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
// ? UI Components:
import Header from './Header.vue';
import Calendar from './Calendar.vue';
import Menu from './Menu.vue';
import TaskView from './TaskView.vue';
// ? Auth components:
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Auth from '../Auth.vue'
// ? Firebase:
import { getAuth } from '@firebase/auth'
import { signOut } from '@firebase/auth'
import { useAuthState } from '../firebase'
// ? Router:
import { useRouter } from 'vue-router'
// ? Store: 
import { useStore } from 'vuex'
// ? ref():
import { ref } from 'vue'


export default {
    components: {
        Header,
        Calendar,
        Menu,
        TaskView,
        Login,
        Register,
        Auth
    },
     name: 'Home',

    setup() {
        /*=============================================
        =            Firebase            =
        =============================================*/
        const { user } = useAuthState()
        const auth = getAuth()  

        const router = useRouter()
        const signOutUser = async () => {
            try {
                await signOut(auth)
                router.push('/auth')
            
            } catch(e) {
                alert(e.message)
            }
        }
        /*=====  End of Firebase  ======*/
        const store = useStore()


        const taskArr = store.state.taskArr
        
    }
}
</script>

Vuex store

index.js

state: () => {
    return {
      cardStatus: false,

      clickedTask: null,
      taskStatus: null,

      dayIsActive: 'active',

      cardVisible: true,
      // The desired array
      taskArr: [ ]
    }
  },

I think that I probably need to use props, but I really have no idea how do I implement this here. Any ideas would be very appreciated!

Javascript: Creating and Calling Dynamic Variables? [duplicate]

I have a script that contains 3 questions. I have started by creating 3 variables (ex: var q1 = “question here”) and I have a function that randomly picks a number between 1 and 3 and chooses that question (var question = “q” + rand;) but if I want to reference this variable called question to output the question in HTML (ex: document.getElement.Id(“output”).innerHTML += question;) how would I do so?

Here is my code:

// Questions List
        var q1 = " Question 1 here"
        var q2 = "Question 2 here"
        var q3 = "Question 3 here"

  // Randomly generate a question and then output it
        var randy = Math.floor(Math.random()*3+1);
        var question = "q" + randy;
        document.getElementById("output").innerHTML += question;
        
    
<!doctype html>
<html>
<body>
  <div id="output"></div>
</body>
</html>

So basically the script will choose a question from 1 to 20 and output it to my HTML div tag.

Sorry if this isn’t clear. Any help is greatly appreciated.

React Native encrypt a message with publicKey. Convert encrypted to base64

I need to do, for react native, encryption of a message.
I tried several libraries, but none worked.
(
JSEncrypt (not supported)
NODERSA (didn’t work)
expo-crypto (I couldn’t set the public key because I have my key)
react-native-rsa (it didn’t work either because of the key)
)

I wonder if anyone knows a way to do this!?


I have the public key and the message.
I need to encrypt the message with the public key and pass it to base64.

Multiple Calls to Custom Hook not yielding expected result

I am having a hard time understanding why the onClick event handler (which invokes 2 calls to a custom hook wrapper function) is not responding properly. I expect that everytime I click the button in the example would swap its border color from green to red based on a value that is being incremented. I understand the example is rudimentary and could easily be solved by conditioning the error prop on the value.value instead of sharing , but this is a simplified example of a more complex interaction, and I have boiled down the issue to a simple example for clarification. Any help would be appreciated.
https://codesandbox.io/s/custom-hooks-with-closure-issue-2fc6g?file=/index.js

Why does my tab don’t change when clicking the button?

I’m developing a new website, with a multi-step form where the steps are all in separated divs. The problem is: when i click in the first button, it shows the second page, but then it goes back to the first.
Here’s my javascript code:

<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
}

function next(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab"); 
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);

}

</script>

My html/php code for first two divs:

 <div class="tab">
    <div id="layout">
        <div class="main">
            <div class="logo">
                <img src="pictures/propcomp.png"/>
            </div>   
            <div class="text">
                <h3 class="blue">Olá!</h3> <br>
                <h3 class="grey">Seja bem vindo(a) à empresa número 1 na pesquisa Google nesse modelo de férias. Bem como já temos mais de 11.300 inscritos no nosso canal no YouTube.</h3>
                <h3 class="blue"><strong>Parabéns!</strong></h3>
                <h3 class="blue normal"><strong class="negrito">Você foi pré-selecionado pelos nossos Analistas de Férias de Alto Padrão </strong> para
                    participar de uma consultoria <strong class="negrito">gratuita e exclusiva</strong> de férias onde na mesma você
                    conhecerá um método de viajar mais e melhor com sua família. Contudo o seu
                    tempo para gente vale ouro, então vamos te presentear com um brinde para que
                    você participe da consultoria. Leia até o final se você quiser saber qual é o brinde!</h3> <br>
            </div>
            <div class="home">
                <a href="">
                <button class="btn btn-beleza" type="button" id="nextBtn" onclick="next(1)">
                 <label class="beleza">Beleza! Quero Participar!</label> 
                <img src="pictures/arrow.svg" />
                </button>
            </a>
            <div class="beneficio">
                <a href="" style="display: flex;"><img src="pictures/interrogacao.svg"/><h4 class="blue normal">Por que estou recebendo esse benefício?</h4></a> 
                
       </div>
            </div>
            <div class="footerimg">
                                 <img style="width:30px; height: 44.5px;"src="pictures/logopequeno.png"/>
                </div>
        </div>
    </div>
</div>

<div class="tab">
<div class="layout">
        <div class="main">
            <div class="text">
                <div class="uausorriso">
                    <h3 class="blue negrito">Uauuuuuuuu, você é demais!!</h3> 
                    <img src="pictures/sorriso.png"/>
                </div>
                <h3 class="grey normal">Te parabenizamos por priorizar suas férias e novas experiências. Aliás, tudo passa e o
                    que fica são os momentos que vivemos com as pessoas que amamos. Afinal, qual é
                    a história que você vai contar?</h3>
                <h3 class="blue normal">Para começar, qual é o seu nome?</h3>
            </div>
            <div class="">
              
                    <input class="inputfield" style="margin-left:32%;"type="text" id="nome" name="nome"><br>
                   
                    <div class="avancar">
                    <a href="">
                    <button class="btn" type="button" id="nextBtn" onclick="next(1)">
                     <h3>Avançar</h3> 
                    <img src="pictures/arrow.svg" />
                    </button>
                </a>
                </div> 
        </div>
    </div>
</div>

I’ve put this online so you can see visually: https://testedeferias.000webhostapp.com/

Vue get params from url & path to app in subfolder of laravel

i used Vue 2.6 for little App with flipbook-vue, and i mounted it in subfolder of my Laravel APP in public/dist/.

I need to get params from url, and i do it like that:

Router index.js:

export default new Router({
  mode: 'history',
  routes: [{ path: "/:numer", component: Newspaper }]
})

vue.config.js:

module.exports = {
  publicPath: '/gazetka/',
}

And in Vue component i use $route.params to get this params.
The problem is that Vue reads the subfodler name dist to me as a parameter.
How do I get around it?
I tried .htaccess but it doesn’t work locally.

Using jQuery UI to open and close search box?

I’m setting up an autocomplete search box.

Here’s my current code:

$(document).ready(function(){
 
 $('#txtSearch').autocomplete({
     source: "https://example.com/search.php",
     minLength: 1,
     select: function(event, ui) {
         var url = ui.item.id;
         if (url != '#') {
             location.href = 'https://' + location.hostname + '/' + url
         }
     },
     open: function(event, ui) {
         $(".ui-autocomplete").css("z-index", 1000)
         $('.exo-search').css('border-bottom-left-radius','0');
         $('.exo-search').css('border-bottom-right-radius','0');
     }
 })
 
});

You can see here that someone starts typing and the results are loading, it sets the bottom border radius to 0.

 open: function(event, ui) {
     $(".ui-autocomplete").css("z-index", 1000)
     $('.exo-search').css('border-bottom-left-radius','0');
     $('.exo-search').css('border-bottom-right-radius','0');
 }

But if someone clicks away from the search box, the dropdown of results disappears like it’s supposed to, but the bottom border radius is still set to 0 instead of resetting back to 5px like it normally is.

Is there something wrong with my code or is that the normal behavior and I need to add something else?

How to put in checkboxes values into a session variable without any button clicks?

lets say i have a code pretty similar like this

<form>
  <input type="checkbox" name="account1" value="1">
  <input type="checkbox" name="account2" value="2">
  <input type="checkbox" name="account3" value="3">
  <input type="checkbox" name="account4" value="4">


  <button type="submit">Delete</button>
</form>

Now i want to store the value of the checkbox in a php session once the user checked the boxes without clicking the submit/delete button. I plan to use jquery/ajax for this but i still cant quite wrap my head around it since im very new to ajax or jquery.

To add more detail, the process is like this..
the user can select any account he wants he checked. lets say he checked an account on page 1. he then went to another page(pagination) and then went back to page 1, the checked boxes would still be checked.

how to read aws cpu usage using node?

i want to build a small app that reads the AWS CPU USAGE every 5 minutes lets say, i built the params, call the getMetricsStatistics but it keeps returning me an empty array, you know why? this is the code:

const aws = require('aws-sdk')
const dotenv = require('dotenv').config()

aws.config.setPromisesDependency()
aws.config.update({
  accessKeyId: process.env.EC2_ACCESS_KEY,
  secretAccessKey: process.env.EC2_SECRET_KEY,
  region: 'us-east-1',
})
const s3 = new aws.CloudWatch()

var params = {
  EndTime: new Date() /* required */,
  /* required */
  MetricName: 'EngineCPUUtilization',
  Namespace: 'AWS/S3',
  StartTime: new Date('Mon Dec 6 2021') /* required */,
  /* required */
  Dimensions: [
    {
      Name: 'Per-Instance Metrics' /* required */,
      Value: 'i-abbc12a7' /* required */,
    },
    {
      Name: 'StorageType',
      Value: 'AllStorageTypes',
    },
    /* more items */
  ],

  Period: 300 /* required */,
  Statistics: ['Average'] /* required */,
}
async function asyncMethod() {
  return await s3.getMetricStatistics(params, function (err, data) {
    if (err) console.log(err, err.stack)
    // an error occurred
    else {
      console.log(data)
    }
  }) // successful response
}

const d = asyncMethod()

response is always empty array in the data.Datapoints.

React.useMemo is re-rendering all items in array

I have a react component that stores a set of fruits in useState. I have a memoized function (visibleFruits) that filters fruits. I map visibleFruits to the dom.

The problem is, when i check a fruit, all visible fruits re-render.

I am expecting that only the selected one re-renders since it is the only one that is changing.

Is there a way for me to use this pattern but prevent all from re-rendering on check?

import React from 'react'

const Example = () => {
    const [fruits, setFruits] = React.useState([
        { id: 1, name: 'apple', visible: true, selected: false },
        { id: 2, name: 'banana', visible: false, selected: false },
        { id: 3, name: 'orange', visible: true, selected: false }
    ])

    const visibleFruits = React.useMemo(() => {
        return fruits.filter((f) => f.visible)
    }, [fruits])

    const handleCheck = (bool, id) => {
        setFruits((prev) => {
            return prev.map((f) => {
                if (f.id === id) {
                    f.selected = bool
                }
                return f
            })
        })
    }

    return (
        <div>
            {visibleFruits.map((fruit) => {
                console.log('** THIS RENDERS TWICE EVERY TIME USER SELECTS A FRUIT **')
                return (
                    <div key={fruit.id}>
                        <input
                            checked={fruit.selected}
                            onChange={(e) => handleCheck(e.target.checked, fruit.id)}
                            type='checkbox'
                        />
                        <label>{fruit.name}</label>
                    </div>
                )
            })}
        </div>
    )
}

export default Example

trying to implement Material Design Navbar in React

I’m scratching my head here trying to figure out why I can’t see the styling applied to my Navbar. I’ve installed all of the necessary modules but it’s not happening. My code is below. I was working on a custom Navbar but the material one is very slick so I wanted to try it instead.

Navbar code

import React, { useState } from 'react';
import {
  MDBContainer,
  MDBNavbar,
  MDBNavbarBrand,
  MDBNavbarToggler,
  MDBIcon,
  MDBNavbarNav,
  MDBNavbarItem,
  MDBNavbarLink,
  MDBBtn,
  MDBDropdown,
  MDBDropdownToggle,
  MDBDropdownMenu,
  MDBDropdownItem,
  MDBDropdownLink,
  MDBCollapse
} from 'mdb-react-ui-kit';

export default function NavbarMaterial() {
  const [showBasic, setShowBasic] = useState(false);

  return (
    <MDBNavbar expand='lg' light bgColor='light'>
      <MDBContainer fluid>
        <MDBNavbarBrand href='#'>Brand</MDBNavbarBrand>

        <MDBNavbarToggler
          aria-controls='navbarSupportedContent'
          aria-expanded='false'
          aria-label='Toggle navigation'
          onClick={() => setShowBasic(!showBasic)}
        >
          <MDBIcon icon='bars' fas />
        </MDBNavbarToggler>

        <MDBCollapse navbar show={showBasic}>
          <MDBNavbarNav className='mr-auto mb-2 mb-lg-0'>
            <MDBNavbarItem>
              <MDBNavbarLink active aria-current='page' href='#'>
                Home
              </MDBNavbarLink>
            </MDBNavbarItem>
            <MDBNavbarItem>
              <MDBNavbarLink href='#'>Link</MDBNavbarLink>
            </MDBNavbarItem>

            <MDBNavbarItem>
              <MDBDropdown>
                <MDBDropdownToggle tag='a' className='nav-link'>
                  Dropdown
                </MDBDropdownToggle>
                <MDBDropdownMenu>
                  <MDBDropdownItem>
                    <MDBDropdownLink>Action</MDBDropdownLink>
                  </MDBDropdownItem>
                  <MDBDropdownItem>
                    <MDBDropdownLink>Another action</MDBDropdownLink>
                  </MDBDropdownItem>
                  <MDBDropdownItem>
                    <MDBDropdownLink>Something else here</MDBDropdownLink>
                  </MDBDropdownItem>
                </MDBDropdownMenu>
              </MDBDropdown>
            </MDBNavbarItem>

            <MDBNavbarItem>
              <MDBNavbarLink disabled href='#' tabIndex={-1} aria-disabled='true'>
                Disabled
              </MDBNavbarLink>
            </MDBNavbarItem>
          </MDBNavbarNav>

          <form className='d-flex input-group w-auto'>
            <input type='search' className='form-control' placeholder='Type query' aria-label='Search' />
            <MDBBtn color='primary'>Search</MDBBtn>
          </form>
        </MDBCollapse>
      </MDBContainer>
    </MDBNavbar>
  );
}

Here’s the code from my App.js with said Navbar

import React from "react";
import { Routes, Route } from 'react-router-dom';
import Header from './components/Header'
import NavbarBasic from './components/NavbarBasic';
import NavbarMaterial from './components/NavbarMaterial';
import About from './components/pages/About';
import Pests from './components/pages/Pests';
import { Ants, Bees, Roaches, Mice, Wasps, Bedbugs, Flies } from './components/Pests';
import Home from './components/pages/Home';
import Services from './components/pages/Services';
import Contact from './components/pages/Contact';

function App() {
  return (
    <div className="main">
      <Header />
      <NavbarMaterial />
      {/* These are the main routes and subpages */}
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/about' element={<About />} />
        <Route path='/pests-we-treat' element={<Pests />} />
        <Route path='/services' element={<Services />} />
        <Route path='/contact' element={<Contact />} />
        <Route path='/ants' element={<Ants />} />
        <Route path='/wasps' element={<Wasps />} />
        <Route path='/roaches' element={<Roaches />} />
        <Route path='/bedbugs' element={<Bedbugs />} />
        <Route path='/bees' element={<Bees />} />
        <Route path='/mice' element={<Mice />} />
        <Route path='/flies' element={<Flies />} />
      </Routes>
    </div>
  );
}

export default App;

Here’s my package JSON file with the dependencies.

{
  "name": "weinerpest",
  "homepage": "http://weinerpestservices.com",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.5.0",
    "@emotion/styled": "^11.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.36",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",
    "@fortawesome/react-fontawesome": "^0.1.16",
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@mui/material": "^5.0.4",
    "@mui/styles": "^5.2.3",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "bootstrap": "^5.1.3",
    "history": "^5.1.0",
    "mdb-react-ui-kit": "^2.1.0",
    "mdbreact": "^5.2.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.3",
    "react-dom": "^17.0.2",
    "react-dropdown": "^1.9.2",
    "react-dropdown-router": "^1.0.1",
    "react-responsive": "^9.0.0-beta.4",
    "react-router-dom": "^6.0.2",
    "react-scripts": "4.0.3",
    "react-select": "^5.2.1",
    "styled-components": "^5.3.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

understanding this when adding new object’s properties/methods (Javascript) [duplicate]

I’m a newbie trying to understand the value of this, when adding a new property and a new method.
Adding new property:

const Person = function (fname, lname) {
    this.fname = fname;
    this.lname = lname;
};
const bob = new Person('Bob', 'Sinclair');
bob.fullName = `${this.fname} ${this.lname}`  

in this example,
this will refer to the global object, therefore the value of fullName will be undefined. I get it.

Adding new method:

bob.printFirstName = function () {
    console.log(this.fname);
}  

now, why is this equal to the object? why, since is a function, is not equal to the global object or undefined (depending we are in non-strict/strict mode), Because is it a method? therefore the this in a method is equal to the object? I don’t get it.