Get gray shade of color with RGB values

I’m trying to create a filter for canvas which draws a monochrome version of an image. I’m drawing the image, then iterating through the image data, then changing those rgb values to a gray, then placing the image data into the canvas. I need help on how to create the gray shade from the rgb values.

My code:

function toGray(vals) {
  var r = vals[0]
  var g = vals[1]
  var b = vals[2]
  // Return gray shade
}
function filter() {
  var c = document.getElementById("canvas1");
  var ctx = c.getContext("2d");
  var img = document.createElement('img')
  img.src = 'shaq.png'
  img.onload = function() {
    ctx.drawImage(img, 0, 0, c.width, c.height);
    var imgData = ctx.getImageData(0, 0, c.width, c.height);
    var i;
    for (i = 0; i < imgData.data.length; i += 4) {
      var rgblist = [imgData.data[i], imgData.data[i+1], imgData.data[i+2]]
      var filtered = toGray(rgblist)
      imgData.data[i] = filtered[0]
      imgData.data[i+1] = filtered[1]
      imgData.data[i+2] = filtered[2]
    }
    ctx.putImageData(imgData, 0, 0);
  }
}
canvas {
  position: absolute;
  bottom: 10px;
  left: 0;
  width: 100vw;
  height: 100vh;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>filter</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <canvas id="canvas1"></canvas>
    <script src="codes.js"></script>
    <script src="filter.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Slider component is breaking on API call in Vue Js

Hi Developers,

I am using splidejs for the vue slider component. I don’t think issue with splidejs. But there is an issue described here.

Issue

There is a slider component. I am making slides dynamic. There two approaches.

Case 1:

Static–

<template>
    <div>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </div>
</template>

Dynamic–
There is an array in data() option. Here

<template>
    <div>
        <li v-for="(slide, index) in slides" :key="index">
           {{ slide.title }}
        </li>
    </div>
</template>

data () {
    return {
        slides: [
          {
            id: 1,
            title: "Best Handmade Goods",
          },
          {
            id: 2,
            title: "Best Cotton",
          },
       ],
   }
}

Result: Working Perfect

Case 2

*I am using api here. API response is 100% okay. No issue with axios. *

<template>
    <div>

        <li v-for="(slide, index) in slides" :key="index">
           {{ slide.title }}
        </li>

    </div>
</template>

data () {
    return {
        slides: null  or // same response on slides: []
    }
},

mounted() {this.fetchSlides()},

methods: {
    async fetchSlides() {
        try {
            const url = "https://fakestoreapi.com/products"
            const response = await axios.get(url)

            this.slides = response.data

            console.log(this.slides)

        } catch (error) {
            console.log(error)
          }
    }
}

API response here in screenshot

api response

Result for case 2: UI break. Slider stop working while API call.

I am expecting a solution from you developers. Please

note:

  1. Issue is not related to splidejs
  2. I am using vue 3 cdn.
  3. All pluigns like axios, splidejs are imported globally. No issue with them

Is there a way to match the _id of one mongodb array to the corresponding clientId from another array?

I have 2 arrays coming from my MongoDB database, one called users that returns a list of user objects like this:

[{
email: "[email protected]",
firstName: "Poe",
lastName: "Damaren",
_id: "bb8"
}]

and one called treatments that has a corresponding clientId that should match the _id from one of the objects in the user array, ie:

[{
clientId: "bb8",
date: "2022-02-04",
treatment "fixed antenna",
_id: "r2d2"
}]

On my client side using React, I’m trying to show a table with a row for every treatments object where the date is greater than today, and then show a column for the date, and a column for the firstName and lastName from the user object whose _id corresponds to the clientId from the treatment object (I hope that makes sense).
I’ve tried putting it together, but I get stuck trying to show the first and last name. This is where I’m at:

<table>
   <thead>
      <tr>
        <th>Date</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      {treatments?.map((t)=>(
         new Date(t?.date) >= today ? (                  
            <tr>
              <td>{t?.date}</td>
              <td>{users?.firstName?.find(u=>u?._id === t?.clientId)}</td>
            </tr>
          ) : (
            <div></div>
          ))
        )}
    </tbody>
</table>

Is there a way to get the first name and last name to show within a table row for each element in the treatments array? Something like this:

Date Name
2022-02-04 Poe Damaren

Help me stackoverflow community, you’re my only hope…

Add Variable in HTML Heading from JQuery Function

working with a highcharts graph, jQuery, and HTML and attempting to get a variable from the jQuery javascript function in to my HTML heading.

I want to get the latest difference/margin from my chart and show it in the heading my page. However, I can’t seem to get the variable from the jQuery function in to HTML and have found no solutions.

<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<script>
   function mainFuncTop2(csv2){
       var linez = csv2.split(/n/)
       const row2 = []
       linez.forEach(row  => {
           row = row.split(',');
           row2.push(row);
       });
       const c1 = []
       const c2 = []

       j = 0;
       row2.forEach(Col1  => {
           if (j == 0) {
               //pass
           } else {

               c1.push(Col1[0]); 
           };
           j++;
       });
       
       k = 0;     
       row2.forEach(Col2  => {
           if (k == 0) {
               //pass
           } else {

               c2.push(Col2[1]); 
           };
           k++;
       });
       var c1R = (c1.filter(Boolean)).map(Number);
       var c2R = (c2.filter(Boolean)).map(Number);        
       difference = c1R.at(-1) - c2R.at(-1)

       var options = {
           xAxis: [{
               endOnTick: true,
               tickPixelInterval: 200,
               title: {
                   text: null,
                   style: {
                       color: 'black'
                   },
               },
               type: 'datetime',
               crosshair: true,
               labels: {
                   style: {
                       fontSize: '12px',
                       color: 'black'
                   },
               },
           }],
           plotOptions: {
               series: {
               pointStart: Date.UTC(2021, 11, 9),
               pointInterval: 24 * 3600 * 1000
           },
       },
           yAxis: [{ //--- Primary yAxis
               startOnTick: false,
               title: {
                   style: {
                       color: 'black'
                   },
               },
               labels: {
                   format: '{value} %',
                   style: {
                       fontSize: '12px',
                       color: 'black'
                   }
               },
               
           }],  
           series: [{
               yAxis: 0,
               name: 'Value 1',
               data: c1R,
               type: 'spline',
               color: '#FF0000',
               lineWidth: 1.5,
           }, 
           {
               yAxis: 0,
               name: 'Value 2',
               type: "spline",
               data: c2R,
               color: '#0000FF',
               lineWidth: 1.5,
           },
           ]
   
       }
   const chart = Highcharts.chart('Chart', options)
   }
   (function($) {
       $(document).ready(function(){
           $.ajax({
               url: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ7lOHrDN86Sudh_-yKIaOP6ugMjqHG0ZFFK2XKtcZ-XW0ZRBRGuRo80NeuPiccJ-ABAWhhFq5vNgna/pub?single=true&output=csv',
               dataType: 'text',
               success: function(data){
                   const csv2 = data
                   mainFuncTop2(csv2)
               }
           });
       });
   })(jQuery);
</script>

<h1 style="text-align:center"> Difference: <span id="difference"></span></h1>
<div id="Chart" style="height: 500px; width: 95%"></div>

The

<h1 style="text-align:center"> Difference: <span id="difference"></span></h1>

at the bottom of my code doesn’t seem to “take” in the “difference” variable in my function and returns empty.

ReactJs the setState is not updating in sync with what is being submitted in the input box

I am not user what is causing the issue. When I input a ticker in the serach bar for example FB the data only renders half of the information but not the calculationModel and addingYear function in the componentDidUpdate, unless I reenter the input variable again in the search bar to get all the information be displayed how it suppose to be I have to renter the same or any other ticker each time to get the information to be properly displayed and I have to take the same steps when I refresh the page.

This is what my component looks like:

    constructor(props) {
        super(props);
        this.state = {
            ticker: "",

            reportDate: "",
            subkey: "",

            FCF: "",
            year: "",

            futureCashFlows: "",

            npv: "",

            terminalValue: "",
            totalPresentValue: "",
            addYear1: "",
            addYear2: "",
            addYear3: "",
            addYear4: "",
            addYear5: ""
        };
    }

    applyData(data) {
        this.setState({
            reportDate: data.reportDate,
            subkey: data.subkey,
            commonShares: data.commonShares,

            year: data.reportDate.slice(0, 4)
        });
    }

    CalulationModel() {
        const DCF_Calulation = calculate(
            this.state.FCF,
            [this.props.growthRate],
            this.props.peRate,
            this.props.discouted,
            2
        );

        this.setState({
            futureCashFlows: DCF_Calulation.futureCashFlows.slice(1, 6),
            totalPresentValue: DCF_Calulation.totalPresentValue,
            npv: Math.pow(1 + this.props.discoutedRate, 5)
        });
    }
    printState() {
        console.log("New state AFTER update");
        console.log(this.state);
    }

    addingYear() {
        // const myDate = moment(this.state.reportDate, "YYYY-MM-DD");
        const myDate = moment(this.state.year, "YYYY");

        this.setState(
            {
                addYear1: myDate.add(1, "y").format("YYYY"), // 2022
                addYear2: myDate.add(1, "y").format("YYYY"), // 2023
                addYear3: myDate.add(1, "y").format("YYYY"), // 2024
                addYear4: myDate.add(1, "y").format("YYYY"), // 2025
                addYear5: myDate.add(1, "y").format("YYYY") // 2026
            },
            this.printState
        );
    }

    componentDidUpdate(prevState) {
        if (this.props.ticker !== prevState.ticker) {
            stockFinancial.stockPulledData(
                this.props.ticker,
                this.applyData.bind(this)
            );

            this.CalulationModel();
            this.addingYear();
        }
    }

Strange change in the behavior of a modal (child component) after setting style.transform to the parent component

I am experiencing a weird change in the appearance or behavior of a modal. The modal is used to enlarge an image sent in a chat. A chat upload preview div is the parent element while the modal is a child element. This strange behavior started happening after I made the chat upload preview draggable with some functions. Under normal conditions, the modal expands and covers the entire screen, going outside of the boundaries of the upload preview (parent component). However, when the chat upload preview is made draggable by adding the transform/translate CSS property to it, the modal only expands and covers the height and width of the upload previewer (parent element). Interestingly enough, if I remove this draggable function (transform/translate), the modal snaps back to its normal behavior, expanding all the way to the edges of the screen. I wonder why adding the transform/translate CSS property to the style of the parent component affects the behavior of the child component. This has really puzzled me. Please help.

Here’s how it would normally look without the transform/translate addition to the parent component (Chat upload preview div):
enter image description here

Here’s how it starts looking after the transform/translate property is added to the parent component (Chat upload preview div):
enter image description here

Here’s the JSX code of the chat upload preview (parent). The modal lives in the FilePreview component whose code is also below.

{/* CHAT-UPLOAD-PREVIEW */}                        
{
    this.state.chatFiles.length > 0 ? 

    <div className="chat-upload-preview-1"
    ref={this.myUploader}
    onMouseMove={this.onMouseMove}
    onMouseDown = {() => {this.setState({pressed: true})}}
    onMouseUp = {() => {this.setState({pressed: false})}}
    >


        <p className="close-button-1" onClick={this.closeUploadPreview}>&#10006;</p>

    <h3 className="chat-upload-preview-title-1">Preview</h3>

    <div className="file-preview-div-1">**<FilePreview files={this.state.chatFiles} 
    deletePreviewfile={this.deletePreviewfile2}
    getReadableFileSizeString={this.getReadableFileSizeString}
    /> </div>**
    
    <div className='chat-upload-container-1'>
    <img src='/images/chat-upload.jpg' alt="upload" height="70" 
    width="70" className='chat-upload-3' onClick={this.inputClick2}>                         
    </img>
                <input className="file-input" type="file" name="file" id="file-1"
                onChange={this.handleChange2} multiple 
                accept=".jpg, .jpeg, .png, .pdf, .doc, .docx"></input> 

                <button className="chat-upload-send-button-1" onClick={this.sendImageToChat}>Send</button>  
    </div> 
    
    </div>
    :
    null

}     

Here’s the code of the FilePreview component which contains the modal’s code too (on the bottom).

import React from 'react'
import './FilePreview.css'

function FilePreview(props) {
    return (
        <div className="image-preview-container">

                            <ul className="image-preview-list">
                            {props.files.map((item) =>                           
                           

                                <li className="image-preview-listItem" key={item.name}>
                                            
                                                                                  
                                            {item.type === "application/pdf"  ?
                                            
                                                // PDF


                                            <div className="pdf-file" >

                                          
                                        <iframe src={URL.createObjectURL(item)} className="iframe-pdf"
                                            height="110" width="100" title="pdf-review">
                                                </iframe>

                                            <a className="pdf-link" href={URL.createObjectURL(item)} target="_blank">view pdf</a>

                                                 <button className="document-image-deleter" onClick={() => props.deletePreviewfile(item)}>x</button>

                                <p className="file-name">{item.name}</p> 
                                <p className="file-size">{props.getReadableFileSizeString(item.size)}</p>    
                                            </div>
                                            
                                            :

                                                    // WORD

                                                                                    
                                            item.type === "application/msword" ?

                                            <div className="pdf-file" >
                                                

                                                <img className="document-image" src="imagesmsword.png" alt="your file" height="50" width="50"/> 

                                                    
                                            <a className="pdf-link" href={URL.createObjectURL(item)} target="_blank">download to view</a>

                                        <button className="document-image-deleter" onClick={() => props.deletePreviewfile(item)}>x</button>

                                <p className="file-name">{item.name}</p> 
                                <p className="file-size">{props.getReadableFileSizeString(item.size)}</p>
                                            </div>

                                            :

                                                    // WORD docx

                                            item.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ?

                                            <div className="pdf-file" >
                                                

                                                <img className="document-image" src="imagesmsword.png" alt="your file" height="50" width="50"/> 

                                                    
                                            <a className="pdf-link" href={URL.createObjectURL(item)} target="_blank">download to view</a>

                                        <button className="document-image-deleter" onClick={() => props.deletePreviewfile(item)}>x</button>

                                <p className="file-name">{item.name}</p> 
                                <p className="file-size">{props.getReadableFileSizeString(item.size)}</p>    
                                            </div>

                                            :

                                                        // Image - Jpeg    

                                            item.type === "image/jpeg" ?   

                                                        

                                            <div className="image-file">

                                          {console.log(URL.createObjectURL(item))}

                                                <img className="document-image" src={URL.createObjectURL(item)} alt="your file" height="50" width="50" 
                                    
                                    onClick={() => {
                                        
                                        const modal = document.getElementById("myModal");
                                        const modalImg = document.getElementById("img01");

                                        modal.style.display = "block";
                                        modalImg.src = URL.createObjectURL(item);

                                    }}>

                                    </img>

                                        <button className="document-image-deleter" onClick={() => props.deletePreviewfile(item)}>x</button>

                                    <p className="file-name">{item.name}</p> 
                                    <p className="file-size">{props.getReadableFileSizeString(item.size)}</p>     

                                            </div>

                                            :
                                                        // Image - png

                                            item.type === "image/png" ?                                               

                                            <div className="image-file">

                                            {console.log(URL.createObjectURL(item))}

                                                <img className="document-image" src={URL.createObjectURL(item)} alt="your file" height="50" width="50" 

                                            onClick={() => {

                                            const modal = document.getElementById("myModal");
                                            const modalImg = document.getElementById("img01");

                                            modal.style.display = "block";
                                            modalImg.src = URL.createObjectURL(item);

                                            }}>

                                            </img>

                                            <button className="document-image-deleter" onClick={() => props.deletePreviewfile(item)}>x</button>

                                            <p className="file-name">{item.name}</p> 
                                            <p className="file-size">{props.getReadableFileSizeString(item.size)}</p>     

                                            </div>

                                            :

                                                         // Others to be added

                                            <div className="image-file">
                                                <img className="document-image" src={URL.createObjectURL(item)} alt="your file" height="50" width="50" 
                                    
                                    onClick={() => {
                                        
                                        const modal = document.getElementById("myModal");
                                        const modalImg = document.getElementById("img01");

                                        modal.style.display = "block";
                                        modalImg.src = URL.createObjectURL(item);

                                    }}>

                                    </img>

                                        <button className="document-image-deleter" onClick={() => props.deletePreviewfile(item)}>x</button>

                                    <p className="file-name">{item.name}</p> 
                                    <p className="file-size">{props.getReadableFileSizeString(item.size)}</p>     

                                            </div>


                                                                                    
                                                                                
                                            }
                                    
                                    


                                    {/* The Image PopUp */}

                                    <div id="myModal" className="modal">

                                                                                  
                                        {/* the close button (x) */}
                                        <span className="close" onClick={() => {
                                            const modal = document.getElementById("myModal");
                                            modal.style.display = "none";
                                        }}>&times;</span>

                                        {/* the image itself */}
                                        <img className="modal-content" id="img01" alt="Something"></img>

                                        {/* Text needs to be added */}
                                        <div id="caption"></div>

                                    </div>


                                </li>
                            )}                                                

                        </ul>                                    
            
        </div>
    )
}

export default FilePreview

Here’s the JSX of the modal again:

 {/* The Image PopUp */}

                                    <div id="myModal" className="modal">

                                                                                   
                                        {/* the close button (x) */}
                                        <span className="close" onClick={() => {
                                            const modal = document.getElementById("myModal");
                                            modal.style.display = "none";
                                        }}>&times;</span>

                                        {/* the image itself */}
                                        <img className="modal-content" id="img01" alt="Something"></img>

                                        {/* Text needs to be added */}
                                        <div id="caption"></div>

                                    </div>

Here’s the function that drags the chat upload preview by adding the transform/translate property to it. It seems to be the culprit in the modal’s strange behavior because when I remove it, the modal behaves well again.

componentDidUpdate () {

        if (this.myUploader.current) {
          this.myUploader.current.style.transform = `translate(${this.state.position.x}px, ${this.state.position.y}px)`
          document.onmouseup = () => {this.setState({pressed: false})}
               
        }
      
        
      }

Here’s the Chat Upload Preview’s (parent component) CSS:

.chat-upload-preview-1 {
    position: absolute;
    bottom: 30px;
    left: 300px;
    background-color: blanchedalmond;
    width: 330px;
    height: 600px;
    border-radius: 20px;
    opacity: 0.9;

}

Here’s the modal’s css:

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0, 0, 0); /* Fallback color */
    background-color: rgba(0, 0, 0, 0.9); /* Black w/ opacity */
    
  }
  
  /* Modal Content (image) */
  .modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
  }
  
  /* Caption of Modal Image */
  #caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
  }
  
  /* Add Animation */
  .modal-content,
  #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
  }
  
  @-webkit-keyframes zoom {
    from {
      -webkit-transform: scale(0);
    }
    to {
      -webkit-transform: scale(1);
    }
  }
  
  @keyframes zoom {
    from {
      transform: scale(0);
    }
    to {
      transform: scale(1);
    }
  }

I just do not know what is happening with the modal once the upload preview has the transform/translate property added to it. Why would it not expand as fully as before the addition of the transform/translate property? I am completely puzzled.

how to join data from an object into a single string in react

I have a variable called color and an object which is like,

let color= "black"
let res = {"Size":128, "Length" : 256}

This object is dynamic like its keys will be incremented by users’ choices. For the whole object, I want to generate a single string that will only have values of the keys concatenated with the color. Like for this object that string will be,

Format : –
COLOR_SIZE_LENGTH

if the object contains a single key then it will look like,

Format : –
COLOR_SIZE

how can I output return only odd friends name from this array in JavaScript [duplicate]

I want to output as a string from this code. I just checked its length but I could not output as a string again like-(‘joy’, ‘james’;). I don’t know where is my problem with the output string. please help to solve this problem. thank you.

function oddFriend(name) {
  let oddFr = [];
  for (let i = 0; i < name.length; i++) {
    let frName = name[i].length;
    console.log(frName);
    if (frName % 2 != 0) {
      oddFr.push(frName);
    }
  }
  return oddFr;
}
console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));

Redux State Management with a Input field

Bit of a noob to redux but this appears to be quite a difficult question! I hope someone may be able to help me 🙂

I have build a page where you can input a search for different types of jobs. From this, it will make a get request to my DB and get all the info on this job. As this page is multi-levelled, I want to use redux to dispatch and pass the state throughout. This will help me pass my data on the job, e.g Data Analyst, through to each component so it can use the data and populate fields.

However, this was how my input field was originally setup:

export function SearchBarComp(props) {

    const [isExpanded, setExpanded] = useState(false);
    const [parentRef, isClickedOutside ] = useClickOutside();
    const inputRef = useRef();
    const [searchQuery, setSearchQuery] = useState("");
    const [isLoading, setLoading] = useState(false);
    const [jobPostings, setjobPostings] = useState([]);
    const [noRoles, setNoRoles] = useState(false)

    const isEmpty = !jobPostings || jobPostings.length === 0;

    const changeHandler = (e) => {
        //prevents defaulting, autocomplete
        e.preventDefault();
        if(e.target.value.trim() === '') setNoRoles(false);

        setSearchQuery(e.target.value);
    }

    const expandedContainer = () => {
        setExpanded(true);
    }


    //LINK THE BACKEND!
    const prepareSearchQuery = (query) => {
        //const url = `http://localhost:5000/api/role/title?title=${query}`;
        const url = `http://localhost:5000/api/role/titlerole?title=${query}`;


        //replaces bad query in the url
        return encodeURI(url);
    }

    const searchRolePosition = async () => {
        if(!searchQuery || searchQuery.trim() === "")
            return;

        setLoading(true);
        setNoRoles(false);

        const URL = prepareSearchQuery(searchQuery);

        const response = await axios.get(URL).catch((err) => {
            console.log(err);
        });


        if(response) {
            console.log("Response", response.data);

            if(response.data && response.data === 0)
                setNoRoles(true);

            setjobPostings(response.data);
        }

        setLoading(false);
    }

    useDebounce(searchQuery, 500, searchRolePosition)

    const collapseContainer = () => {
        setExpanded(false);
        setSearchQuery("");
         setLoading(false);
         setNoRoles(false);
        if (inputRef.current) inputRef.current.value = "";

      };

    // console.log("Value", searchQuery)

    useEffect(()=> {
        if(isClickedOutside)
            collapseContainer();
    }, [isClickedOutside])

    return (
    <SearchBarContainer animate = {isExpanded ? "expanded" : "collapsed"} 
                        variants={containerVariants} transition={containerTransition} ref={parentRef}>
        <SearchInputContainer>
            <SearchIconSpan>
                <SearchIcon/>
            </SearchIconSpan>
            <SearchInput placeholder = "Search for Roles" 
                                onFocus={expandedContainer} 
                                ref={inputRef}
                                value={searchQuery}
                                onChange={changeHandler}
                                />
            <AnimatePresence>
                {isExpanded && (<CloseIconSpan  key="close-icon" 
                                inital={{opacity:0, rotate: 0}} 
                                animate={{opacity:1, rotate: 180}} 
                                exit={{opacity:0, rotate: 0}} 
                                transition={{duration: 0.2}}
                                onClick={collapseContainer}>
                    <CloseIcon/>
                </CloseIconSpan>
                 )}
            </AnimatePresence>
        </SearchInputContainer>
        {isExpanded && <LineSeperator/>}
        {isExpanded && <SearchContent>

        {!isLoading && isEmpty && !noRoles && (
        <Typography color="gray" display="flex" flex="0.2" alignSelf="center" justifySelf="center">
                Start typing to search
        </Typography>
        )}
        
        {!isLoading && !isEmpty && <>
            {jobPostings.map((searchRolePosition) => (
                <JobSection
                    title={searchRolePosition.title}
                    //will need to do something like ----
                    //people = {searchRolePosition.title && searchRolePosition.title.average}
                    // future implementations
                />
            ))}    
        </>}
      
        </SearchContent>}
    </SearchBarContainer>
    )
}

As you can see, the main thing is the ‘query’ this creates a backend request to my titlerole, such as getting the data on Data Analyst. This all works in my frontend right now, but I can’t pass that data down to the next component etc

So i’m looking to use redux.

I’ve created the following slice:

import { createSlice } from "@reduxjs/toolkit";

const jobSearchSlice = createSlice({
  name: "jobsearch",
  initialState: {
    currentRole: null,
    isFetching: false,
    error: false,
  },
  reducers: {
    jobsearchStart: (state) => {
      state.isFetching = true;
    },
    jobsearchSuccess: (state, action) => {
      state.isFetching = false;
      state.currentRole = action.payload;
    },
    jobsearchFailure: (state) => {
      state.isFetching = false;
      state.error = true;
    },
  },
});

export const { jobsearchStart, jobsearchSuccess, jobsearchFailure } = jobSearchSlice.actions;
export default jobSearchSlice.reducer;

With this, I’m also using the following apiCalls.js file:

import { jobsearchStart, jobsearchSuccess, jobsearchFailure } from "./jobsearchSlice";
import { publicRequest } from "../requestMethods";
export const roleSearchQuery = async (dispatch, jobsearch) => {
  dispatch(jobsearchStart());
  try{
    const res = await publicRequest.get("`http://localhost:5000/api/role/titlerole?title=${query}`", jobsearch);
    dispatch(jobsearchSuccess(res.data))
  }catch(err){
    dispatch(jobsearchFailure());
  }
};

My question is as a Redux noob, how do I implement this query functionality into a redux API request? What’s the way to do this properly as I begin to tranisition this to an app which uses standard state management!

How to avoid vite build deleting inside of “dist” directory?

I want to create multiple libraries by vite, so I try “rollupOptions” first. Like,

import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        "qy-viewer": 'src/qy-viewer.ts',
        "qy-swiper": 'src/qy-swiper.ts'
      }
    }
  }
})

But this create funny results including hash-like string, like qy-swiper.f3fc032d.js.
This is useless, so I gave up this approach.

Next I try preparing multiple vite config files. Like,

vite.qy-swiper.config.ts

import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    lib: {
      entry: 'src/qy-swiper.ts',
      name: 'QySwiper',
      fileName: (format) => `qy-swiper.${format}.js`
    },
    rollupOptions: {
    }
  }
})

vite.qy-viewer.config.ts

import { defineConfig } from 'vite'

export default defineConfig({
  build: {
    lib: {
      entry: 'src/qy-viewer.ts',
      name: 'QyViewer',
      fileName: (format) => `qy-viewer.${format}.js`
    },
    rollupOptions: {
    }
  }
})

package.json

{
  "scripts": {
    "build:swiper": "tsc && vite build --config vite.qy-swiper.config.ts",
    "build:viewer": "tsc && vite build --config vite.qy-viewer.config.ts",
    "build:lib": "npm run build:swiper && npm run build:viewer"
  },
}

This works very fine when I execute npm run build:swiper or npm run build:viewer independently, but once I execute npm run build:lib, only qy-viewer is created.
Are there any way to avoid deleting files in dist directory by vite build ?

Activate class=”animate__animated animate__bounce” on click

I am learning html and css and I want to use this library: https://animate.style/

I have this code

<head>
  <link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
  />
</head>

https://codepen.io/wmfznuiy-the-looper/pen/jOaMXXg

NUESTROS SERVICIOS

I want the effect to work when clicking. I used this code but it didn’t work

$("#hola").click(function() {
  $('.animate__animated .animate__bounce-active').toggleClass('.animate__animated .animate__bounce-active');
});

I have read many post and followed what they say but it is not working. I am new, please help. Thank you

Filter String/Array for multiple conditions

This is my code below, basically i want the bot to check two things. The users message needs to contain “how” + either “doing” or “bread”. It works perfectly when i use only “doing” but not when I add the “bread” condition.
I need a clean and simple solution for this and hope someone can help me, bc for me thats the most logical way in archiving what i need 😀

if(msg.content.includes("how") && msg.content.includes("doing" || "bread") ){

    if(msg.author != token){ 
        msg.lineReply("I am good sir")
        }

}