TypeError: setFilteredData is not a function

I’m currently trying to implement a filter component in my app to filter points shown on a map based on the selection of a dropdown box. The error occurs when I choose a selection from the dropdown menu and it occurs within my Filter Component which handles the onChange event to filter the data within my state.
Any help would be greatly appreciated!

enter image description here

App.js

import React from 'react';
import Map from './components/Map/Map'
import Sidebar from './components/Sidebar/Sidebar'
import { useState, useEffect } from 'react';
import "./app.css"

function App() {

  const url = "/data"
  const [data, setData] = useState([])
  const [filteredData, setFilteredData] = useState([])

  useEffect(()=>{
    const fetchData = async () => {
      const jobs = await fetch(url)
      const jobsData = await jobs.json();
      setData(jobsData)
      setFilteredData(jobsData)
    }
    fetchData()
  },[])

  

  return (
    <div className="app">
      <Map data={data} setData={setData} filteredData={filteredData} setFilteredData={setFilteredData}/>
      <Sidebar data={data} setData={setData} filteredData={filteredData} setFilteredData={setFilteredData}/>
    </div>
  );
}

export default App;

Sidebar.jsx

import React from 'react';
import Filter from '../Filter/Filter';
import "./sidebar.css"

function Sidebar(data, setData, filteredData, setFilteredData) {
    
    return (
        <div  style = {{float: "right", height: "97vh", width: "30%"}} className="sidebar" >
            <h1>Job Filters</h1>
            <Filter data={data} setData={setData} filteredData={filteredData} setFilteredData={setFilteredData}>
            </Filter>
        </div>
    );
}

export default Sidebar;

Filter.jsx

import React from 'react';
import "./filter.css"


export function Filter(data, setData, filteredData, setFilteredData) {

    const handleChangePriority = (e) =>{
        if(e.target.value === "all"){
            setFilteredData(data)
        }else{
            const result = [data].filter(job => job.priority === e.target.value)
            setFilteredData(result)
        }
    }

    const handleChangeStatus = (e) => {
        console.log(e.target.value)
    }
    return ( 
        <div className="wrapper">
            <div className="priority">
                <div className="box">
                    <h1>Priority: </h1>
                    <select className="priority-list" id="priority-list"  onChange={handleChangePriority}>
                        <option value="all">All</option>
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                    </select>
                </div>
            </div>
            <div className="status">
                <div className="box">
                    <h1>Status: </h1>
                    <select className="status-list" id="status-list" onChange={handleChangeStatus}>
                        <option value="all">All</option>
                        <option value="completed">Completed</option>
                        <option value="in-progress">In-Progress</option>
                        <option value="assigned">Assigned</option>
                        <option value="unassigned">Unassigned</option>
                    </select>
            </div>
            </div>
        </div>
    );
}

export default Filter;

How to add custom local JS files in Gatsby correctly

I´m a newbie on react and gatsby but i´m working on a little project as practice anda I have a little problem. I want to add a custom JS file to the project (little functions for a calculator on the index). I used Helmet to import them and on develop enviroment is working fine, but once build, is not.

import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"

export default function homePage() {
  return (
    <main>
      <Helmet>
        <script src={withPrefix('/functions.js')} type="text/javascript" />
        <script src={withPrefix('/escritura.js')} type="text/javascript" />
      </Helmet>
}

I´m not sure what I am doing wrong. Someone can help me, please? You can see the project proof version live here:

https://modest-hoover-aac2d1.netlify.app/

In the final version, every input should be filled automatically, but is not happening.

Why does adding a second dropdown mess up the JS to close menu when user clicks outside it?

I’m not super familiar with JS. I used the W3Schools tutorial for creating an on-click dropdown menu as a reference and added a second menu. However, only the second dropdown menu listed in the javascript maintains the functionality of closing when the user clicks outside the dropdown. (I can switch the order of the functions listed in the JS, and changing nothing else, that switches which menu has that close-when-click-outside functionality.)

Can anyone help me understand why that is? How to fix it would be a bonus but mostly I just don’t get why it works for one menu and not the other.

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function drop1() {
  document.getElementById("drop1").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn1')) {
  var drop1 = document.getElementById("drop1");
    if (drop1.classList.contains('show')) {
      drop1.classList.remove('show');
    }
  }
}

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function drop2() {
  document.getElementById("drop2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn2')) {
  var drop2 = document.getElementById("drop2");
    if (drop2.classList.contains('show')) {
      drop2.classList.remove('show');
    }
  }
}
.navbar {
  overflow: hidden;
  background-color: #333;
  font-family: Arial, Helvetica, sans-serif;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropbtn1, .dropbtn2 {
  cursor: pointer;
  font-size: 16px;  
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover, .dropdown:hover .dropbtn, .dropbtn:focus {
  background-color: red;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<div class="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <div class="dropdown">
  <button class="dropbtn1" onclick="drop1()">Dropdown
    &nbsp; +
  </button>
  <div class="dropdown-content" id="drop1">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  </div> 
  <div class="dropdown">
  <button class="dropbtn2" onclick="drop2()">Dropdown 2
    &nbsp; +
  </button>
  <div class="dropdown-content" id="drop2">
    <a href="#">Link 4</a>
    <a href="#">Link 5</a>
    <a href="#">Link 6</a>
  </div>
  </div>
</div>

<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Click on the "Dropdown" link to see the dropdown menu.</p>

Thank you!

Detecting Webpack mode in JavaScript files

I am building a bundle of ReactJS files with Webpack.

Is it possible to detect inside of JSX files which Webpack mode is being used: "none", "development", or "production"?

For example, I would like some console.log() statements and global variables in development mode but not production.

nodejs + aws elasticache redis connection timed out

I am using redis 4.0.0 in my NodeJS application to connect to a aws redis cluster.
I get a connection timed out. What am I doing wrong?

    const redisUrl = 'redis://xyz.use1.cache.amazonaws.com:6379';
    const redisClient = redis.createClient({ url: redisUrl });
    await redisClient.connect();

xyz.use1.cache.amazonaws.com is the primary-endpoint of the cluster

Is it possible to attach multiple functions in V-for?

I have an array of elements, I need to render those elements in to a div and attach different on-click functions to each.

<template>
  <div class="container">

    <div v-for="option in options" :key="option.id" @click="option.clickFunction">. 
      {{option}}
    </div>

  </div>
</template>

<script>
export default{
  data(){
    return{
      options: [
        {
          id: 1,
          text: "option 1",
          clickFunction: "function1",
        },
        {
          id: 2,
          text: "option 2",
          clickFunction: "function2",
        },
        {
          id: 3,
          text: "option 3",
          clickFunction: "function3",
        },
        {
          id: 4,
          text: "option 4",
          clickFunction: "function4",
        },
        {
          id: 5,
          text: "option 5",
          clickFunction: "function5",
        },
      ],
    }
  }
  methods:{
    //defining all click functions
  }
}
</script>

I have tried the above approach but its not working, is there any way of doing this?

ejecutar funciones dentro del mismo objeto literal javascript [closed]

María, contenta con el trabajo que realizaron, les pide otra funcionalidad extra. Resulta que a la concesionaria le suelen preguntar muy seguido cuáles de los autos para la venta son 0 km. Tené en cuenta que María considera que un auto 0 km es aquel que tenga un kilometraje menor a 100. Vas a tener que desarrollar la funcionalidad autosNuevos.

¿Cómo se resuelve esto reutilizando la función autosParaLaVenta?

tengo este codigo

´´´

let autos=[{
    marca:"Ford",
    modelo:"Fiesta",
    color:"Azul",
    anio:2019,
    km:200,
    precio:150000,
    cuotas:12,
    patente:"APL123",
    vendido:false
    },{
        marca:"Toyota",
    modelo:"Corolla",
    color:"Blanco",
    anio:2019,
    km:0,
    precio:100000,
    cuotas:14,
    patente:"JJK116",
    vendido:true
    }];
     module.exports  = autos;

´´´

y este es el objeto

´´´

var autos = require ("./autos");
const concesionaria = {
    
   autos: autos,
   buscarAuto : function buscar(patente) {
    let autoSalida = null
    this.autos.forEach(auto => {
        if(auto.patente === patente){
            autoSalida = auto
        }
    })
    return autoSalida
},
 venderAuto: function (patente) {
    const auto = this.buscarAuto(patente);
    if (auto) {
      auto.vendido = true;
    }
    return auto 
},
autosParaLaVenta: function(autos){
   return autos = this.autos.filter(function (autos){
          return autos.vendido===false;
       })
}, autosNuevos : function(autos){
 const auto = this.autosParaLaVenta(function(autos){

     if (auto.km<100){
         return auto
     }
 });

}           

}

´´´

Have A File Download Link/Button Also Update A MySQL Database

I have a download button on a form that updates a MySQL database, and updates the number of downloads/the download count of a file. I thought I’d be able to add the download attribute to this form button and provide the url to the file so the file would also download. It seems you can only use the download attribute on anchor <a> links. That in itself isn’t an issue, I can just style the anchor link like I have the button – but how can I get it so when someone clicks the <a> link, as well as downloading the image, it also submits data to the database?

Simplified version of form button that submits to MySQL database:

<form method="post">
    <button type="submit" name="download">Download</button>
    <input type="hidden" name="filename" value="<?php echo $image_filename; ?>">
</form>

A ‘download’ file link:

<a download href="localhost/project/image/file.jpg">Download</a>

I’ve also included the PHP function that updates the database for reference purposes. This function is called on the page itself where the images are downloaded. Note: $connection is the database connection code that is imported at the top of the functions.php file where this function is.

PHP

function downloadCounter($connection, $filename) {
    if (isset($_POST['download'])) {
        // value from a hidden form element which outputs the filename
        $filename = $_POST['filename'];

        try {
            $sql = "UPDATE lj_imageposts SET downloads = downloads +1 WHERE filename = :filename";
            $stmt = $connection->prepare($sql);

            $stmt->execute([
                ':filename' => $filename
            ]);


        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
    }
}

How to select all input in the form of images with text and checkboxes

I want to create a method that when run will check all inputs that have images and text, where this method will run on the input checkbox with the label Select All. Like the example I made on the imageChecked() method which worked successfully where when the input is checked, the checked image data will be entered/returned to the image array in crudData{‘image’:[]}, and the text input data will be entered/returned to the array name in crudData{‘name’:[]}. Does anyone understand the case I’m asking about? Thank you.

Here is the complete code https://jsfiddle.net/ntkpx7c0/5/

<script>
export default {
    data() {
        return{
            crudData:{
                'id': null,
                'name': [],
                'image': [],
                'arrImage': [],
            },
        }
    },
    methods: {
        imageUpload(e, maxItem){                    
            ....
        },
        uploadImage(e){
            ...
        },
        removeImage(key){
            ...
        }, 
        imageChecked() {
            let checkedImages = this.crudData.arrImage.filter(img => img.checked)
            this.crudData.image = checkedImages.map(img => img.image)
            this.crudData.name = checkedImages.map(img => img.name)
            console.log({imageFiles: this.crudData.image, names: this.crudData.name})
        }
    }


}

Number of days from two dates

I am using this below function to calculate number of days between dates. So if date is greater than today’s date then it calculates the number of days from today’s date which seems to be working fine but when the date is less than today’s date and when date is from October it calculates the dates in opposite direction where as it should print Available today. Some examples of date i am facing issue is below like
if date is 2021-10-31 and today’s date is 2021-12-11 then it gives 42 days but it should give Available today
if date is 2021-11-01 and today’s date is 2021-12-11 then it gives Available today

if( currentDish.ServingDateFrom){
                  if(!isNaN(currentDish.ServingDateFrom)){
                    if(currentDish.ServingDateFrom.getDate()<=nowDate.getDate()){
                      availability = "Available Today";
                      console.log("Available Today");
                    }else if(currentDish.ServingDateFrom.getDate()>nowDate.getDate()){
                      var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                      var diffDays = Math.round(Math.abs((currentDish.ServingDateFrom.getTime() - nowDate.getTime()) / (oneDay)));
                      availability = "Available in " + diffDays + " Days";
                      console.log(nowDate, " - ", currentDish.ServingDateFrom);
                      console.log("Available in " + diffDays + " days");
                    }
                  }
                }

Why I cant choose content type when upload png image from javascript to minio

How can i upload an image from js to minio?

I tried this code.

minioClient.putObject('image-test', this.state.Img.name, this.state.result, 'image/png', function(err, etag) {
  if (err) return console.log(err)
  console.log('File uploaded successfully.')
});

i set content type as ‘image/png’ but on minio server i still got ‘binary/octet-stream’
enter image description here

and this is how I get file

 handleImageChange(e) {
  e.preventDefault();
  var reader = new FileReader();
  var file = e.target.files[0];
  reader.onloadend = () => {
  console.log('file name—',file);
  console.log('file result—',reader.result);
  this.setState({
    Img: file,
    result: reader.result
  });
 }
  reader.readAsDataURL(file)
}

the input component looks like

      <Button
        variant="contained"
        component="label"
        fullWidth
      >
        Upload File
        <input
          type="file"
          hidden
          onChange={e => this.handleImageChange(e)}
        />
      </Button>