Check if state array contains object id, JavaScript

I’m developing an app which has to fetch new orders from the Firestore database, I used componentDidMount to refresh the screen every 10 seconds and launch the fetchNewOrders function, if new orders are available, the function should push that object into the state array newOrder, and display the orders in the FlatList below. When I start the code it returns the error TypeError: undefined is not an object (evaluating 'item.id'), I also wrote the example of an array I’m fetching from the database.

Screen

   export default class Received extends Component {
      constructor(props) {
        super(props);
        this.state = {
          loaded: false,
          newOrder: [],
        };
      }

    async componentDidMount() {
        this.updateTimer = setInterval(() => {
          this.fetchNewOrders();
          }, 10000);
      }
    
        fetchNewOrders = async () => {
            const querySnapshot = await getDocs(collection(db, path));
            if(querySnapshot.length !== 0) {
              querySnapshot.forEach((doc) => {
                let array = this.state.newOrder;
                const data = doc.data().order;
                data.map(({obj, id}) => {
                  const filter = array.find(c => c.id === id);
                  if (filter == undefined) {
                    array.push(obj)
                    this.setState({ newOrder: array })
                  }
                })
              })
            }
          }

render() {

        return (
          <View>
            <FlatList
              data={this.state.newOrder}
              keyExtractor={item => item.id}
              renderItem={({ item }) => {
                return (
                  <TouchableOpacity>
                    <Text>{item.serviceRequested}</Text>
                    <View>
                      <Tex>${item.total}</Text>
                    </View>
                  </TouchableOpacity>
                )
              }}
            />
          </View>
        )
      }
}

data (new order)

Array [
  Object {
    "date": "Mon Feb 28 2022 11:24:14 GMT-0500 (EST)",
    "id": 0.9436716663143794,
    "instructions": "",
    "order": Array [
      /////////////
    ],
    "paymentType": "Cash",
    "serviceRequested": "Delivery",
    "total": 10.4,
  },
]

MongoDB: How to get and display items by userID

I’m trying to get and display all entries in an ‘item’ collection that contain and are listed by a user/userID.

item_controller.js:

const Item = require('../models/item_schema')

const getUserItems = (req, res) => {
    Item.findById(req.params.userID).populate('categoryID').populate('qualityID').populate('userID')
    .then((data) => {
        if (data) {
            res.status(200).json(data)
        } else {
            res.status(404).json(`Item from user id ${req.params.userID} not found.`)
        }
    })
}

module.exports = {
    getUserItems
}

item_schema.js:

const { Schema, model} = require('mongoose')

const itemSchema = new Schema({
    title: {
        type: String,
        required: [true, 'Title field is required.']
    },
    description: {
        type: String,
        required: [true, 'Description field is required.']
    },
    userID: {
        type: Schema.Types.ObjectId,
        ref: "User",
        required: [true, 'User field is required']
    },
    categoryID: {
        type: Schema.Types.ObjectId,
        ref: "Category",
        required: [true, 'Category field is required']
    },
    qualityID: {
        type: Schema.Types.ObjectId,
        ref: "Quality",
        required: [true, 'Quality field is required']
    },
    price: {
        type: Number
    },
    claimed:{
        type: Boolean
    }
}, {
    timestamps: true
})

module.exports = model('Item', itemSchema)

server.js:

const express = require('express')
const cors = require('cors')
const jwt = require('jsonwebtoken')

require('dotenv').config()
require('./db')()

const { getUserItems } = require('./controllers/item_controller')

const port = process.env.PORT || 3000

const app = express()
app.use(cors())
app.use(express.json())

app.use((req, res, next) => {
    if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        jwt.verify(req.headers.authorization.split(' ')[1], 'zero_waste_app', (err, decode) => {
            if (err) req.user = undefined
            req.use r = decode
            next()
        })
    } else {
        req.user = undefined
        next()
    }
})

// Item Routes 
app.get('items/user/:userID', getUserItems)

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

I think my problem is in the item_controller, I’ve tried a few different ways, such as Item.find({userID: userID}), but I can’t get it to work. Does anyone know what I’m doing wrong and how I can fix it?

why does this function return [‘y’,’e’,’s’]?

can someone please explain it to me how does this function return [‘y’,’e’,’s’] instead of just the string ‘yes’ ????
the value of num first will be 8 then else condition will work then num will be [5,6,7] and again the else condition will work then num finally becomes an empty array [] which will fullfill the if condition then it should return ‘yes’ but it doesn’t!?

function ABC(num, ...rest) {
  if (num < 5) {
    return 'yes';
  } else {
    return [...ABC(rest)];
  }
};
console.log(ABC(8, 5, 6, 7));

When I open the modal, the api call running always

I’d like that if I click onto a link and the modal is open the api call runs one time.
Unfortunately it’s running always, till the open state is true.

const [open, setOpen] = useState(false);
const [content, setContent] = useState();

const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);

const fetchData = async (movieName) => {
console.log("Fetching");
const { data } = await axios.get(
  `https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&utf8=1&formatversion=latest&srsearch="${movieName}" articletopic:films`
);

setContent(data);
console.log(data);

};

if (open) {
fetchData();

}

Is there a way to reset or save filtered data when moving between pages in a website?

I am working a website where there is a function to filter data based on one common data, when I move to a different page after setting the filter, the data that is filtered is displayed again when I move back to that page but the filter itself is rest. So I need either the filter to be saved as well or the data to be reset. The filter only exists on this one page as well.

Would welcome any suggestions at all as I am well and truly stumped.

using Base64 images in react.js

I am trying to use Base64 encoded images in my react app.

currently I load images from a folder and looks something like this:

<img className="..." src={imageFile}></img>

I want to use base64 encoded images, I think I can do this:

<img className="..." src={"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH...."}></img>

the problem is that the base64 strings are huge, and for some reason I cant store them in my component.
I tried putting them in a txt file and doing:

fs.readFile('image.txt', function(err, data){console.log(data);})

but I get tons of errors, including:

Uncaught TypeError: fs.readFile is not a function

among others.

any ideas how to store base64 strings in a separate file and load them into my component?

Thanks!

How to use tailwind with rsuite

Can anyone tell, How can we use tailwind with rsuite? without overriding.
I would like to use tailwind with rsuite , by when I use rsuite , I was not able to tailwind.Can anyone tell me how to solve this problem?

Reactjs: useState value not work in useEffect

This is my code:

const getFirstData = async () => {
    // fetch data and get defaultOrder
    setDefaultOrder("x")
}

const getOrder = async () => {
    // fetch data with defaultOrder
}

useEffect(() => {
    const fetchData = async () => {
        await getFirstData()
        await getOrder()
    }

    fetchData();

}, [defaultOrder]);

This code work fine, but I have 2 problems:

1- First time load, my code run twice. beacuse defaultOrder changed in getFirstData

2- With every change getFirstData, whole of useEffect run again!

How to convert Swiper.js into ES5

I use babel to convert it but the swiper is not working and it shows this error in console.

enter image description here

I go to the line where this error happen and add console.log().

enter image description here

There’s no problem getting these elements but somehow $(...).each just doesn’t work.

enter image description here

What can i do to fix this?

Or is there something wrong when converting?

My .babel is simple, as below

{
  "presets": ["es2015"]
}

displaying cards with load more functionality

// Fetching the data from JSON
fetch("data.json")
  .then((response) => response.json())
  .then((data) => appendData(data))
  .catch((err) => console.log(err));

// Create main container with divs inside
function appendData(data) {
  let mainContainer = document.getElementById("myData");
  for (let i = 0; i < data.length; i++) {
    // children divs of the main div
    let div = document.createElement("div");

    // Profile picture
    let profilePic = document.createElement("img");
    profilePic.src = data[i].profile_image;
    profilePic.setAttribute("class", "profilePic");
    div.appendChild(profilePic);

    //Facebook Name

    let name = document.createElement("h3");
    name.innerHTML = data[i].name;
    name.setAttribute("class", "name");
    div.appendChild(name);

    // Date
    let date = document.createElement("h5");
    date.setAttribute("class", "date");
    let months = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ];
    let current_datetime = new Date(data[i].date);
    let formatted_date =
      current_datetime.getDate() +
      " " +
      months[current_datetime.getMonth()] +
      " " +
      current_datetime.getFullYear();
    date.innerHTML = formatted_date;

    div.appendChild(date);

    // Facebook
    let facebookicon = document.createElement("span");
    facebookicon.innerHTML = `<svg width="30" height="25" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M7.98371 0.0333252C3.57448 0.0333252 0 3.6078 0 8.01704C0 11.9716 2.87829 15.2467 6.65219 15.8809V9.6827H4.72629V7.45218H6.65219V5.80751C6.65219 3.89923 7.81771 2.85932 9.52029 2.85932C10.3357 2.85932 11.0365 2.92009 11.2399 2.94685V4.94151L10.059 4.94209C9.13333 4.94209 8.95486 5.3819 8.95486 6.02751V7.45104H11.1637L10.8756 9.68155H8.95486V15.9342C12.905 15.4535 15.9673 12.095 15.9673 8.01475C15.9673 3.6078 12.3929 0.0333252 7.98371 0.0333252Z" fill="#1778F2"/>
    </svg>`;
    facebookicon.setAttribute("class", "facebookicon");
    div.appendChild(facebookicon);

    // Image
    let img = document.createElement("img");
    img.src = data[i].image;
    img.setAttribute("class", "img");
    div.appendChild(img);

    // Caption under the image
    if (!!data[i].caption.length) {
      let caption = document.createElement("p");
      caption.innerHTML = data[i].caption;
      caption.setAttribute("class", "caption");
      div.appendChild(caption);
    }

    // Like heart icon
    let likeicon = document.createElement("button");
    likeicon.innerHTML = `<svg width="17" height="17" viewBox="0 0 17 17" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M14.7617 3.26543C14.3999 2.90347 13.9703 2.61634 13.4976 2.42045C13.0248 2.22455 12.518 2.12372 12.0063 2.12372C11.4945 2.12372 10.9878 2.22455 10.515 2.42045C10.0422 2.61634 9.61263 2.90347 9.25085 3.26543L8.50001 4.01626L7.74918 3.26543C7.0184 2.53465 6.02725 2.1241 4.99376 2.1241C3.96028 2.1241 2.96913 2.53465 2.23835 3.26543C1.50756 3.99621 1.09702 4.98736 1.09702 6.02084C1.09702 7.05433 1.50756 8.04548 2.23835 8.77626L2.98918 9.52709L8.50001 15.0379L14.0108 9.52709L14.7617 8.77626C15.1236 8.41448 15.4108 7.98492 15.6067 7.51214C15.8026 7.03935 15.9034 6.53261 15.9034 6.02084C15.9034 5.50908 15.8026 5.00233 15.6067 4.52955C15.4108 4.05677 15.1236 3.62721 14.7617 3.26543V3.26543Z" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>`;
    likeicon.setAttribute("class", "likeicon");
    likeicon.setAttribute("id", "button" + i);
    div.appendChild(likeicon);
    let buttonfunction = (a) => {
      a;
    };
    buttonfunction("button" + [i]);

    // Number of likes
    let numberOfLikes = document.createElement("span");
    numberOfLikes.innerHTML = data[i].likes;
    numberOfLikes.setAttribute("class", "numberOfLikes");
    div.appendChild(numberOfLikes);

    // Append the children divs to the main div container
    mainContainer.appendChild(div);
  }
}
body {
  font-family: Arial, Helvetica, sans-serif;
}
#myData {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: space-evenly;
  align-items: baseline;
}
#myData div {
  width: 19.5em;
  margin: 10px 0;
  position: relative;
  border: 1px solid rgba(0, 0, 0, 0.171);
  padding: 18px 5px;
}
#myData div .img {
  width: 100%;
  height: auto;
  overflow: hidden;
  margin-top: 20px;
}
#myData div .profilePic {
  width: 3.2em;
  object-fit: cover;
  height: 3.2em;
  border-radius: 100px;
  -webkit-border-radius: 100px;
  -moz-border-radius: 100px;
  -ms-border-radius: 100px;
  -o-border-radius: 100px;
  display: inline;
  margin-left: 0;
}
#myData div h3.name {
  display: inline;
  margin: 0;
  padding: 0;
  position: relative;
  bottom: 25px;
  left: 10px;
  font-size: 1.3em;
}
#myData div button {
  border: none;
  background-color: white;
  position: relative;
  top: 2px;
}

#myData div h5 {
  display: inline;
  margin: 0;
  padding: 0;
  position: relative;
  bottom: 5px;
  left: -105px;
  font-size: 0.8em;
  font-weight: 100;
}
#myData div span.facebookicon {
  position: relative;
  top: -12px;
  right: -36px;
}

#myData div p.caption {
  padding: 0 2px 15px 2px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.171);
}

@media screen and (max-width: 768px) {
  #myData div {
    width: 100%;
    margin: 10px 5px;
  }
  #myData div span.facebookicon {
    position: absolute;
    top: 30px;
    right: 20px;
  }
}
button#loadmore {
  margin: 50px auto;
  display: block;
  font-size: 1.5em;
  border: none;
  background-color: #1778f2;
  border-radius: 50px;
  -webkit-border-radius: 50px;
  -moz-border-radius: 50px;
  -ms-border-radius: 50px;
  -o-border-radius: 50px;
  padding: 15px 25px;
  cursor: pointer;
  color: azure;
}
button#loadmore:hover {
  color: rgba(65, 65, 65, 0.685);
  background-color: #177af2dc;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TASK frontendk</title>
    <link rel="stylesheet" href="/style.css" />
  </head>
  <body>
    <body>
      <div id="myData"></div>
      <button id="loadmore">Load More</button>
    </body>
    <script src="./js.js"></script>
  </body>
</html>

//Json file

[
{
    "image": "https://placekitten.com/600/400",
    "caption": "Duis in facilisis lectus. Nulla molestie erat erat, quis tempor enim sodales vitae. Sed tempus, libero fringilla rhoncus ullamcorper, justo elit dignissim ex, nec elementum quam sem in urna.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2018-03-12 03:00:00",
    "likes": "123",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/100/100"
},
{
    "image": "https://placekitten.com/600/410",
    "caption": "Quisque metus nisi, consequat et molestie eget, facilisis ac odio. Nam lorem libero, efficitur ac velit at, egestas tempor arcu. Nullam pharetra ex eget orci lobortis malesuada. Maecenas eget porta felis. Aliquam porttitor, nibh nec ullamcorper fermentum, eros velit lobortis justo, pretium consectetur turpis enim ut nunc. Fusce convallis, ex ut ultrices sodales, ante quam venenatis arcu, vitae mollis magna urna vel eros. Aliquam a sapien nisi. Nullam convallis malesuada suscipit. ",
    "type": "image",
    "source_type": "instagram",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2019-01-12 03:00:00",
    "likes": "0",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/150/100"
},
{
    "image": "https://placekitten.com/600/420",
    "caption": "",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2017-01-21 03:00:00",
    "likes": "9866555",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/100/150"
},
{
    "image": "https://placekitten.com/600/430",
    "caption": "Etiam eu blandit nisi. Aliquam rutrum faucibus mauris, sed egestas odio viverra at. In elementum sit amet sapien vitae bibendum.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-12-12 03:00:00",
    "likes": "2",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/120/120"
},
{
    "image": "https://placekitten.com/600/440",
    "caption": "Vivamus a sem sit amet nisi pretium pretium. Curabitur blandit ut lectus non bibendum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris leo odio, consectetur a lorem vitae, aliquet placerat orci. Phasellus varius ante sit amet quam mollis, eu efficitur tortor blandit.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2018-04-12 03:00:00",
    "likes": "12343",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/50/50"
},
{
    "image": "https://placekitten.com/600/440",
    "caption": "Duis in facilisis lectus. Nulla molestie erat erat, quis tempor enim sodales vitae. Sed tempus, libero fringilla rhoncus ullamcorper, justo elit dignissim ex, nec elementum quam sem in urna.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-12-12 03:00:00",
    "likes": "123",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/101/101"
},
{
    "image": "https://placekitten.com/800/400",
    "caption": "Duis in facilisis lectus. Nulla molestie erat erat, quis tempor enim sodales vitae. Sed tempus, libero fringilla rhoncus ullamcorper, justo elit dignissim ex, nec elementum quam sem in urna.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-12-12 03:00:00",
    "likes": "12",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/150/120"
},
{
    "image": "https://placekitten.com/600/500",
    "caption": "Vivamus a sem sit amet nisi pretium pretium. Curabitur blandit ut lectus non bibendum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris leo odio, consectetur a lorem vitae, aliquet placerat orci. Phasellus varius ante sit amet quam mollis, eu efficitur tortor blandit.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2017-12-12 03:00:00",
    "likes": "23",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/140/140"
},
{
    "image": "https://placekitten.com/700/400",
    "caption": "Pellentesque lacinia volutpat turpis non fermentum. Cras at pellentesque augue. Aliquam eget metus sit amet turpis consectetur posuere.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2017-12-08 03:00:00",
    "likes": "0",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/100/100"
},
{
    "image": "https://placekitten.com/700/500",
    "caption": "Duis in facilisis lectus. Nulla molestie erat erat, quis tempor enim sodales vitae. Sed tempus, libero fringilla rhoncus ullamcorper, justo elit dignissim ex, nec elementum quam sem in urna.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-02-12 03:00:00",
    "likes": "0",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/102/102"
},
{
    "image": "https://placekitten.com/800/600",
    "caption": "Aliquam odio libero, malesuada et iaculis a, facilisis bibendum dolor. Vivamus ultricies congue arcu eu porttitor. Integer libero tortor, volutpat a purus id, mattis tristique tortor. ",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-12-12 03:00:00",
    "likes": "2",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/103/100"
},
{
    "image": "https://placekitten.com/700/600",
    "caption": "Duis in facilisis lectus.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2020-12-12 03:00:00",
    "likes": "1",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/40/100"
},
{
    "image": "https://placekitten.com/1600/1400",
    "caption": "Nulla molestie erat erat, quis tempor enim sodales vitae. Sed tempus, libero fringilla rhoncus ullamcorper, justo elit dignissim ex, nec elementum quam sem in urna.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-12-15 03:00:00",
    "likes": "2324",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/80/100"
},
{
    "image": "https://placekitten.com/1600/400",
    "caption": "Aliquam odio libero, malesuada et iaculis a, facilisis bibendum dolor.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-10-12 03:00:00",
    "likes": "1223",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/80/80"
},
{
    "image": "https://placekitten.com/2000/4000",
    "caption": "Quis tempor enim sodales vitae. Sed tempus, libero fringilla rhoncus ullamcorper, justo elit dignissim ex, nec elementum quam sem in urna.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2016-12-12 03:00:00",
    "likes": "12223",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/110/110"
},
{
    "image": "https://placekitten.com/900/600",
    "caption": " Suspendisse finibus lorem nibh, facilisis ullamcorper nunc consequat sit amet. Curabitur ultricies magna ante, ac eleifend lorem auctor porta. Nullam volutpat aliquet lorem, et posuere ex aliquet eu. Quisque elementum sem mauris, a mattis est scelerisque vitae. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut quis massa eget ligula euismod sagittis id congue quam. Duis vestibulum eros sed tincidunt rutrum. Pellentesque in malesuada velit.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2017-12-12 03:00:00",
    "likes": "0",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/110/100"
},
{
    "image": "https://placekitten.com/600/410",
    "caption": "Quisque metus nisi, consequat et molestie eget, facilisis ac odio. Nam lorem libero, efficitur ac velit at, egestas tempor arcu. Nullam pharetra ex eget orci lobortis malesuada. Maecenas eget porta felis. Aliquam porttitor, nibh nec ullamcorper fermentum, eros velit lobortis justo, pretium consectetur turpis enim ut nunc. Fusce convallis, ex ut ultrices sodales, ante quam venenatis arcu, vitae mollis magna urna vel eros. Aliquam a sapien nisi. Nullam convallis malesuada suscipit. ",
    "type": "image",
    "source_type": "instagram",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2019-01-12 03:00:00",
    "likes": "0",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/150/100"
},
{
    "image": "https://placekitten.com/600/420",
    "caption": "",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2017-01-21 03:00:00",
    "likes": "9866555",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/100/150"
},
{
    "image": "https://placekitten.com/600/430",
    "caption": "Etiam eu blandit nisi. Aliquam rutrum faucibus mauris, sed egestas odio viverra at. In elementum sit amet sapien vitae bibendum.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://www.facebook.com/EmbedSocial/",
    "date": "2019-12-12 03:00:00",
    "likes": "2",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/120/120"
},
{
    "image": "https://placekitten.com/600/440",
    "caption": "Vivamus a sem sit amet nisi pretium pretium. Curabitur blandit ut lectus non bibendum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris leo odio, consectetur a lorem vitae, aliquet placerat orci. Phasellus varius ante sit amet quam mollis, eu efficitur tortor blandit.",
    "type": "image",
    "source_type": "facebook",
    "source_link": "https://instagram.com/embedsocial/",
    "date": "2018-04-12 03:00:00",
    "likes": "12343",
    "name": "John Smith",
    "profile_image": "https://placekitten.com/g/50/50"
}

]

When the page is opened, four cards should be loaded and displayed.
When a Load More button is clicked, it should open another four cards. Clicking the Load More button should keep loading four more cards every time until all
cards are loaded, at which point the Load More button should be hidden.
● The hearth icon should be clickable. When it is clicked, the likes counter should increase
and the heart icon should change color. When the heart icon is clicked once again, the
‘like’ should be removed, the likes counter should decrease and the heart icon should
revert to the original color.

If someon could help me with this amd explain the process. Thank you very much.

Download a folder from URL as a zip in Javascript

I am looking for an implementation which allows downloading a file from a path as a zip

I have copy this code: https://cheatcode.co/tutorials/how-to-create-and-download-a-zip-file-with-node-js-and-javascript

Howeve, when i try to download a folder a run into this error:

       download(f) {
      if (!f) f = this.state.selectedItem;
      let links = f.map((obj)=>{
        return this.backend().directLink(obj.id, true);
      })
      this.downloadAndZip(links);
  }

downloadByOne = url => {
    return fetch(url).then(resp => resp.blob());
  };
   downloadByGroup = (urls, files_per_group=5) => {
    return Promise.map(
      urls,
      async url => {
        return await this.downloadByOne(url);
      },
      {concurrency: files_per_group}
    );
  }
   exportZip = blobs => {
    const zip = JsZip();
    if(Array.isArray(blobs))
    blobs.forEach((blob, i) => {
      zip.file(`file-${i}`, blob);
    });
    else
    zip.file(`file`, blobs);
    zip.generateAsync({type: 'blob'}).then(zipFile => {
      const currentDate = new Date().getTime();
      const fileName = `combined-${currentDate}.zip`;
      return FileSaver.saveAs(zipFile, fileName);
    });
  }
   downloadAndZip = urls => {
return this.downloadByGroup(urls, 5).then(this.exportZip);

}

}

Is there any way of download a directory as a zip from a URL? i am using webix file manager

is there any file manager which does this?

Variables in javascript are not enough to hold a value [closed]

I’m doing web scraping with javascript.

I’m wondering how I can store all the html code in a variable called websiteContent ?

Because according to my understanding javascript has only 3 types of variables var let and const , all of which are not enough to store at all.

What should I do?

This is my code:

function test() {
  var url = "https://pantip.com/topic/34943783"

  
  //fetch site content

  var websiteContent = UrlFetchApp.fetch(url);
  var fetchTime = Utilities.formatDate(new Date(), 'Etc/GMT', "yyyy-MM-dd HH:mm:ssZ"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"

  //extract data

  var laDeathsRegExp = new RegExp(/(?<=title>)(.*)(?= - Pantip)/m);
 
  var laDeathsMatchText = laDeathsRegExp.exec(websiteContent);

  Logger.log(websiteContent.getContentText());

  Logger.log('' + laDeathsMatchText);
}

Can’t get getElementsByClassName or querySelectorAll to work

Here’s a fiddle that i (partly) got to work with the queryselector. http://jsfiddle.net/03rc2j91/
It only hides the first element as it should. But i need to hide all the elements with the same class.

I’m working on a project where i need to target the same class to hide all the images within that class.

I tried using querySelectorAll but it didn’t work. Same problem with getElementsByClassName()

Queryselector is the only one i got to work but it’s not enough to hide just the first element.

Your help would be much appreciated,
Thanks!

function toggleBoxVisibility() {

  if (document.querySelector(".check").checked == true) {

    document.querySelector(".box").style.opacity = '0';

  } else {

    document.querySelector(".box").style.opacity = '1';

  }
}

Can anybody give me the code to create a collapsible navbar for my website.?

Actually, I wanted to make the navbar collapsible when a user click on the three bars. It is working fine in Desktop mode, but in mobile mode, it is not working. So anybody, who can give me the working code.?

Here is my code for mobile version of nav bar :-

” class=”mobile_profile_image” alt=””>

View Profile
Edit Profile
“>Assignments
Forms
About
Settings

[enter image description here][1]

How to have click events for iterated links

I have an asp.net app, on the app’s dashboard the names of websites are pulled through to the view from a SQL DB like this.

 <h1>My Websites</h1>

 

  

 @{

        foreach (var website in Model.websites)
        {
            <table>
                <tr>

                    <td>  <a id="websiteLink" href="">@website </a> </td>

                </tr>

            </table>
        }

}

which works fine:

pic of websites pulled from db

I am trying to have a click event for each of the website links, in order to pull info based on the clicked website.

 <script>

        var website_link = document.getElementById("websiteLink");

        website_link.addEventListener("click", function () {
//test the click event
            alert("link clicked");
        })

       

    </script>

But the click event only works on the first link? when I inspect the page at runtime with chrome devs tools, the correct ID is added to the second link but the click event does not fire? Please help me.

My goal is to render information based on the clicked link, I basically just need the html.value of the clicked link to complete my task…

Thank you in advance for any suggestions!