Hos to add Redux to this code and split it into smaller components in react app

This code will grow larger and is not easy to maintain nor scalable, I am planning to add Redux but don’t know how to do it, I also want to spli the code into smaller components

/* eslint-disable jsx-a11y/anchor-is-valid */
//App.js
import React, { useState, useCallback } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import './App.css';
import Footer from './components/footer/Footer';
import filteredData from './components/data/filteredData';

function Testing({ handleCategoryClick, handleSearchChange }) {
  console.log(handleCategoryClick, handleSearchChange);
  return (
    <div>
      <h1>Hello</h1>     
    </div>
  );
}

function Articles({ handleCategoryClick, handleSearchChange }) {
  console.log(handleCategoryClick, handleSearchChange);
  return (
    <div>
      <h1>Wasabito</h1>      
    </div>
  );
}

function CategoryLink({ cat, selectedCategory, handleCategoryClick }) {
  const isActive = selectedCategory === cat;
  const handleClick = useCallback(() => handleCategoryClick(cat), [handleCategoryClick, cat]);

  return (
    <span
      className={`nav-link-second p-2 d-none d-md-block ${isActive ? 'active' : ''}`}
      style={{ cursor: 'pointer' }}
      onClick={handleClick}
    >
      {cat}
    </span>
  );
}

function Card({ item }) {
  return (
    <div className="col-md-4 mb-3" key={item.id}>
      <div className="card">
        <div className="card-body">
          <div className="frame-color"></div>
          <p className="card-text">{item.category}</p>
          <p className="card-text">{item.description}</p>
          <Link to={item.pagePath} className="btn btn-primary">
            {item.text}
          </Link>
        </div>
      </div>
    </div>
  );
}

function App() {
  const itemsPerPage = 9;
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');

  const handlePageChange = useCallback((pageNumber) => {
    setCurrentPage(pageNumber);
    }, []);
    
    const handleCategoryClick = useCallback((category) => {
    setSelectedCategory(category);
    setCurrentPage(1);
    }, []);
    
    const handleSearchChange = useCallback((event) => {
    setSearchTerm(event.target.value);
    setCurrentPage(1);
    }, []);
    
    const filteredCards = filteredData.filter((item) => {
    const { category, text, description } = item;
    const lowerCaseSearchTerm = searchTerm.toLowerCase();
    return (
    (!selectedCategory || selectedCategory === 'All' || category === selectedCategory) &&
    (category.toLowerCase().includes(lowerCaseSearchTerm) ||
    text.toLowerCase().includes(lowerCaseSearchTerm) ||
    description.toLowerCase().includes(lowerCaseSearchTerm))
    );
    });
    
    const totalCards = filteredCards.length;
    const totalPages = Math.ceil(totalCards / itemsPerPage);
    const indexOfLastCard = currentPage * itemsPerPage;
    const indexOfFirstCard = indexOfLastCard - itemsPerPage;
    const currentCards = filteredCards.slice(indexOfFirstCard, indexOfLastCard);
    const pageNumbers = Array.from({ length: totalPages }, (_, i) => i + 1);
    
    return (
    <Router>
    <div>
    {selectedCategory === null && (
    <div className="p-3 mb-2 bg-primary text-white" style={{ background: 'linear-gradient(to right, #00c6ff, #0072ff)', marginTop: '20px' }}>
    Mas Verificaciones
    </div>
    )}
        <div className="nav-scroller py-1 mb-2 custom-class1">
      <nav className="nav d-flex justify-content-between px-3">
        <h2>
          <a href="/">
            <img src="logo.png" alt=" " />
          </a>
        </h2>
        {[
          'Estados Unidos',
          'Mexico',
          'America Latina',
          'Resto del Mundo',
          'Covid-19',
          'Salud',
          'Medio Ambiente',
          'Guerra en Ucrania',
        ].map((cat) => (
          <CategoryLink
            key={cat}
            cat={cat}
            selectedCategory={selectedCategory}
            handleCategoryClick={handleCategoryClick}
          />
        ))}
      </nav>
    </div>

    <div className="container">
      <div className="row">
        <div className="col-md-12 mb-3">
          <input
            type="text"
            className="form-control"
            placeholder="Search..."
            value={searchTerm}
            onChange={handleSearchChange}
          />
        </div>
      </div>
    </div>

    <Routes>
  <Route
    path="/"
    element={
      <>
        <div className="container">
          <div className="row">
            {currentCards.map((item) => (
              <Card key={item.id} item={item} />
            ))}
          </div>
        </div>

        <nav aria-label="...">
          <ul className="pagination justify-content-center">
            <li className={`page-item ${currentPage === 1 ? 'disabled' : ''}`}>
              <a
                className="page-link"
                href="#"
                onClick={() => setCurrentPage(currentPage - 1)}
                tabIndex="-1"
              >
                Previous
              </a>
            </li>
            {pageNumbers.map((number) => (
              <li key={number} className={`page-item ${currentPage === number ? 'active' : ''}`}>
                <a className="page-link" href="#" onClick={() => setCurrentPage(number)}>
                  {number}
                </a>
              </li>
            ))}
            <li className={`page-item ${currentPage === totalPages ? 'disabled' : ''}`}>
              <a className="page-link" href="#" onClick={() => setCurrentPage(currentPage + 1)}>
                Next
              </a>
            </li>
          </ul>
        </nav>
      </>
    }
  />
  <Route path="/" element={<App />} />
   <Route path="/testing/:id" element={<Testing handleCategoryClick={handleCategoryClick} handleSearchChange={handleSearchChange} />} />
   <Route path="/articles/:id" element={<Articles handleCategoryClick={handleCategoryClick} handleSearchChange={handleSearchChange} />} />
</Routes>

<Footer />
  </div>
</Router>
);
}

export default App;



 //components/data/filteredData.js
 const filteredData = [
  {
    id: 1,
    category: "Mexico",
    pagePath: "/articles/1",
    text: "Learn More",
    description: "loren ipsum loren ipssum loren ipsum"
  },
  {
    id: 2,
    category: "Estados Unidos",
    pagePath: "/testing/1",
    text: "Learn More",
    description: "loren ipsum loren ipssum loren ipsum"
  },
 ]
  export default filteredData;

I have installed the Redux package using npm and created a Redux store in my application. I have not defined reducers and actions to handle the state management. In my components, I expected that after integrating Redux, I would be able to store and manage the application state centrally. I wanted to be able to dispatch actions to update the state and access the updated state in my components

I don’t understand why the code is not updated

I am working on a web programming project, when I make changes to my code they are not reflected in the page, it seems that the previous instruction stays loaded as a local server I am using xammp.

This is the image of the code that I have enter image description here

and this is the code that the browser has, it is an earlier version than the one I have: enter image description here

I already tried to close and open xampp again thinking that was the problem, but it still doesn’t work.

Evaluating security of my escape function with XSS

I made a javascript function that takes an input and escapes it, returning a div string with the text as an example. Is this escape function susceptible to XSS attacks, and if so, what is the issue?

function escape(s) {
    s = s.toString()
    if (s.length > 100) { throw new Error("Too long!") }
    s = s.replace(/./g, function(x) {
        return { '<': '&lt;', '>': '&gt;', '&': '&amp'}[x] || x;       
    });
    if (s.match("prompt") || s.match("alert")) { throw new Error("XSS caught") }
    return "<div>"+s+"</div>"
}

No errors, I would just like to know if my function is vulnerable

Convert a HLS Stream in MP4 with Javascript

I need the client to download a live streaming .flv/.m3u8 from an external cdn and for the client to convert it to mp4.

Everything needs to be done with javascript, do you have any ideas? I specify that it has to be done client side.
I use this code to download the file, but I have no idea how to convert it to mp4 directly while downloading

Code:

function downloadFile(url) {
  const link = document.createElement('a');
  link.href = url;
  link.download = url.split('/').pop();
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
const url = 'https://getsamplefiles.com/download/flv/sample-1.flv';
downloadFile(url);

Using Chakra UI’s useClipboard hook

I have multiple input fields populated with data gotten from redux store. I need help to implement a copy to clipboard function for each input field. Tried doing this but no luck:

import { useClipboard } from "@chakra-ui/react";

const { sandboxKey, token } = useSelector((state) => state.apikeys);
  
const { onCopy, value, setValue, hasCopied } = useClipboard("");

return (
 <InputGroup>
   <Input 
     value={token}
     onChange={(e) => {
     setValue(e.target.value);
     }}
     />
   <InputRightElement>
     <Button onClick={onCopy}>
      {hasCopied ? "Copied!" : "Copy"}
     </Button>
   </InputRightElement>
 </InputGroup>
 
 <InputGroup>
   <Input 
     value={prodkey.prodKey}
     onChange={(e) => {
     setValue(e.target.value);
     }}
     />
   <InputRightElement>
     <Button onClick={onCopy}>
      {hasCopied ? "Copied!" : "Copy"}
     </Button>
   </InputRightElement>
 </InputGroup>
)

Background color is not rendering for the created nodes

I am trying to implement Path Finding Visualizer tutorial by Clement . I am new with the react. The color for the start and the end node is not getting rendered.

Please take a look at my files:

PathVisualizer.css :

.grid{
    margin: 500px 500 500;
    margin-top: 100px;
}

PathVisualizer.jsx :

import React, {Component} from "react";
import Node from './Node/Node';
import './Node/Node.css'

import './PathfindingVisualizer.css';


export default class PathfindingVisualizer extends Component{
    constructor(props){
        super(props);
        this.state={
        nodes: [],
        };
    }
    componentDidMount() {
        const nodes=[];
       
        for(let row=0; row<20; row++){
            const currentRow=[];
            for(let col=0; col<50; col++){
                const currentNode={
                    col,
                    row,
                    isStart : row === 10 && col === 5,
                    isFinish : row === 10 && col === 45 ,
                };
                
                currentRow.push(currentNode);
            }
            nodes.push(currentRow);
        }
        this.setState({nodes});
    }
    render(){
        const {nodes}=this.state;
        console.log(nodes);

        return(
            <div className="grid">
                {nodes.map((row,rowIdx)=>{
                    return(
                        <div key={rowIdx}>
                            {row.map((node,nodeIdx) => {
                            const {isStart, isFinish} = node;
                            return(
                                
                                <Node>
                                    key={nodeIdx}
                                    isStart={isStart}
                                    isFinish={isFinish}
                                    test={'foo'}
                                    test={'kappa'}
                                </Node>
                            );
                        })}
                        </div>
                    );
                    })}
                
            </div>
        );
    }
}

Node.css :

.node {
    width: 25px;
    height: 25px;
    grid-gap: 20px;
    outline: 1px solid rgb(94, 93, 93);
    display: inline-block;
  }

.node-finish {

  background-color: rgba(181, 6, 6, 0.751) !important;
}

.node-start {
  background-color: rgb(4, 178, 4)!important;
}

Node.jsx :

import React, {Component} from "react";

import './Node.css';

export default class Node extends Component{
    constructor(props){
        super(props);
        this.state={}
    }

    render(){
        const {isFinish, isStart} = this.props
        const extraClassName = isFinish 
        ? 'node-finish'
        : isStart ? 'node-start'
        : '';
        return <div className ={`node ${extraClassName}`}></div>
        
    }

}

export const DEFAULT_NODE={
    row:0,
    col:0,
}; 

These are my files. I am getting the output of the grid rendered correctly. But the node color for that specific mentioned nodes are not changing. Please help me out in the same.

Thanks.

Convert markdown with katex to pdf file electron

I’m using electron with react to create a markdown editor. For now it renders correctly any katex.
enter image description here
I am using a npm library called md-to-pdf. And I made it work until I realized that it doesn’t render any katex:
enter image description here

How can I use md-to-pdf to achieve my goal?
Here’s the code for the editor:

import { ChangeEvent, RefObject, KeyboardEvent } from "react";
import { Box, Flex, Textarea } from "@chakra-ui/react";
import ChakraUIRenderer from "chakra-ui-markdown-renderer";
import ReactMarkdown from "react-markdown";
import rehypeKatex from "rehype-katex";
import rehypeRaw from "rehype-raw";
import remarkMath from "remark-math";
import remarkGfm from "remark-gfm";
import remarkBreaks from "remark-breaks";
import remarkEmoji from "remark-emoji";
import "katex/dist/katex.min.css";

interface EditorProps {
  val: string;
  onEdit: (e: ChangeEvent<HTMLTextAreaElement>) => void;
  onKeyDown: (e: KeyboardEvent<HTMLTextAreaElement>) => void;
  txRef: RefObject<HTMLTextAreaElement>;
}

function Editor({ val, onEdit, onKeyDown, txRef }: EditorProps) {
  return (
    <Flex h="100%" justifyContent="center" gap="0.5rem">
      <Textarea
        ref={txRef}
        value={val}
        onChange={onEdit}
        onKeyDown={onKeyDown}
      />
      <Box
      >
        <ReactMarkdown
          components={ChakraUIRenderer()}
          skipHtml
          remarkPlugins={[remarkGfm, remarkMath, remarkBreaks, remarkEmoji]}
          rehypePlugins={[rehypeKatex, rehypeRaw]}
          children={val}
        />
      </Box>
    </Flex>
  );
}

And here is what I tried to use to make the pdfs:

let sReq = await dialog.showSaveDialog(mainWindow, {
  title: "Save PDF",
  filters: [{ name: "PDF", extensions: ["pdf"] }]
});

if (sReq.canceled) return;

let pdf = await mdToPdf({ content: md }).catch(console.error);
if (pdf) {
  writeFileSync(sReq.filePath!, pdf.content);
}

Nextjs 13 new fetching method not working

so I’m making a website using Next13 and I’m trying to retrieve specific data from my sanity client using in a dynamic route server component using the new minimalistic fetching but I get nothing, I have my console logs and looks like everything is matching up in the query but nothings gets fetched..

import React from 'react'
import { client } from '@/lib/sanityClient';



export default async function Page({params}) {


  const query = `*[type == "project" && _id == "${params.id}"]`;

  const project = await client.fetch(query , { cache: 'force-cache' });
  
  console.log(query);
  console.log(project)

  return (
    <div>
      <h1> Dummy static text</h1>
      <h1>{project.name}</h1>
      <p>{project.description}</p>
    </div>
  )
}

enter image description here

enter image description here

My setTimeout function doesnt work and I dont know why?

I’m making a function that displays a window when all the inpuit boxes have info and I want the new window to close after 5 seconds but my setTimeout doesnt work

            function processInput()
            {
                //if statement checks if all fields contain something
                //or true, if not they are falsy
                if(nameInput.value && phoneNumber.value && adress.value)
                {
                    //New Window size and centering
                    let winWidth = 300;
                    let winHeight = 300;
                    let leftPosition = ((screen.width - winWidth)/2);
                    let topPosition = ((screen.height - winHeight)/2);

                    //String that contains onptions for the new Window
                    let options = "width =" + winWidth + ",height=" 
                                + winHeight + ", left =" + leftPosition
                                + ", top =" + topPosition;
                    //creates a new window
                    let confWindow = window.open("confirm.htm", 
                    "Confirm Page", options);

                    //Setting a timer for the new window to close after 
                    //5 seconds
                    setTimeout(() => {
                        confWindow.close();
                    }, 5000);

                    //making the new window the main window
                    //confWindow.focus();
                }
                else{
                    window.alert("Please Enter Information in all fields");
                }

Web App Google Apps Script – Conditional input based on the data selected in a select

In order to obtain the necessary code to get a function that can be executed every time a local is selected in “id-local” and that what it does is the following: with the data that this input has

<form class="row g-12 " id="facturacion-form"> 

    <div class="col-md-3 input-group-lg has-validation"> 

     <label for="id-local" class="form-label">LOCAL</label> 

     <select class="form-select" id="id-local" name="id-local" required> 

       <option selected>Elije local</option> <?!=options?> 

     </select> 

  <div class="invalid-feedback"> Por favor elige un local 
  </div> 
</div> 

look in the google sheets sheet: “XXXXXXXXX”, in the sheet with name “DB_LOCALES” in the range “B:O” where in “B” are the name of the premises and in “O” are the name of the companies corresponding, so that in this other input

<div class="input-group "> 

   <span class="input-group-text">Sociedad</span> 

   <input type="text" class="form-control" id="sociedad-local" placeholder="Cooland Proyect S.L" aria-label="sociedad-local" aria-describedby="sociedad-local"> 

</div>

At the moment I have the following function:

function updateSociedad() {
  
  var libroLocales = SpreadsheetApp.openById("XXXXXXXXXXX");
  var hojaLocales = libroLocales.getSheetByName("DB_LOCALES");
  var rangesoc = hojaLocales.getRange("B:O");
  
  var values = rangesoc.getValues();
  
  var local = document.getElementById("id-local").value;
  
  for (var i = 0; i < values.length; i++) {
    if (values[i][0] == local) {
      // Actualizar el valor del campo "sociedad"
      var sociedad = values[i][14]; // Columna "O"
      document.getElementById("sociedad-local").textContent = sociedad;
      break;
    }
   console.log(values);
  }
}

but if I put it in the .gs it gives me errors that it can’t access the document.getElementById but if I put it in the HTML it shows me that it can’t access the spreadsheet

My intention was to create a call to the function from another input, but it is being impossible due to my lack of experience.

I would greatly appreciate help

Destructured vs non-destructured value in React Context

This is a simple context example code.

When you run this code and press ‘TRUE’ and ‘FALSE’ button respectively. You will only see, ‘Getter is rendered’ in console.log which is what I want.

<Example Code: 1>

import { createContext, useState, useContext, Dispatch, SetStateAction } from 'react';
import { Button, Text } from 'react-native';

const SetterContext = createContext<any>( () => undefined);
const GetterContext = createContext<boolean>(false);

const App = () => {
    return (
        <Provider>
            <>
                <Getter />
                <Setter />
            </>
        </Provider>
    );
};

const Provider = ({ children }: { children: any }) => {
    const [isFoo, setIsFoo] = useState(false);
    return (
        <GetterContext.Provider value={ isFoo }>
            <SetterContext.Provider value={ setIsFoo }>
                {children}
            </SetterContext.Provider>
        </GetterContext.Provider>
    );
};

const Getter = () => {
    console.log('Getter is rendered');
    const getter = useContext(GetterContext);
    return (
        <Text>{getter ? "TRUE":"FALSE"}</Text>
    )
}

const Setter = () => {
    const setIsFoo = useContext(SetterContext);
    console.log('Setter is rendered')
    return (
        <>
            <Button title="True" onPress={ () => {setIsFoo(true)}}></Button>
            <Button title="False" onPress={ () => {setIsFoo(false)}}></Button>
        </>
    )
}

export default App;

However, (see below code),
When I call a setter function in a destructive way, now I see both console.log is printed which means both components are rendered at this time.

It prints both, ‘Getter is rendered’ and ‘Setter is rendered’ when the state is changed

<Example Code: 2>

import { createContext, useState, useContext, Dispatch, SetStateAction } from 'react';
import { Button, Text } from 'react-native';

const SetterContext = createContext<any>( () => undefined);
const GetterContext = createContext<boolean>(false);

const App = () => {
    return (
        <Provider>
            <>
                <Getter />
                <Setter />
            </>
        </Provider>
    );
};

const Provider = ({ children }: { children: any }) => {
    const [isFoo, setIsFoo] = useState(false);
    return (
        <GetterContext.Provider value={ isFoo }>
            <SetterContext.Provider value={{ setIsFoo }}>
                {children}
            </SetterContext.Provider>
        </GetterContext.Provider>
    );
};

const Getter = () => {
    console.log('Getter is rendered');
    const getter = useContext(GetterContext);
    return (
        <Text>{getter ? "TRUE":"FALSE"}</Text>
    )
}

const Setter = () => {
    const { setIsFoo } = useContext(SetterContext);
    console.log('Setter is rendered')
    return (
        <>
            <Button title="True" onPress={ () => {setIsFoo(true)}}></Button>
            <Button title="False" onPress={ () => {setIsFoo(false)}}></Button>
        </>
    )
}

export default App;


Both example codes are almost the same, the only difference is described below.

<Example Code in Summary: 1>

This example prints only, ‘Getter is rendered’ when the state is changed.

// Set directly
<SetterContext.Provider value={ setIsFoo }>

// Call directly
const setter = useContext(SetterContext);

<Example Code in Summary: 2>

This example prints both, ‘Getter is rendered’ and ‘Setter is rendered’ when the state is changed.

// Set in Destructive
<SetterContext.Provider value={{ setIsFoo }}>

// Call in Destructive
const { setIsFoo } = useContext(SetterContext);

Can you explain why it re-renders both components when ‘setIsFoo’ is called in a destructive way?

I want to make it render the getter component only when the state is changed.

Javascript CSV Data Parcing

I am attempting to parse a CSV file using Javascript, and I almost have what I need, but I am having a hard time finding the correct code to use in my specific scenario.

I am attempting to go down to a certain line/row in the CSV data, and delete certain text in the data file for that specific line/row.

I have worked with Javascript before, but the specific way I am trying to get this code to work, other methods I have researched and tried are not giving me the results I want.

In Highbyte, a service which we’re using to gather equipment data, they give users the option to use Javascript to parse the data. Here is what I have tried doing so far:

In Highbyte, I am using {{Connection.EQ001309.ViCellSampleResults}}, which gathers data specific to the path (in my case EQ001309.ViCellSampleResults).This is the data that is returned
In my Javascript, I have the following code: {{Connection.EQ001309.ViCellSampleResults}}[15][“Vi-CELL XR 2.06.3”]. This successfully grabs the row of data, and pulls out the “Vi-Cell XR 2.06.3” column of data.This is the data that is returned
However, I would like to parse the data to read: “Viable_Cell_Density” : 596
I have a good understanding on what I need to do, as far as having to use the function str.replace(“Viable cells : “, “”).
Where I am having troubles is implementing that with the current line of code {{Connection.EQ001309.ViCellSampleResults}}[15][“Vi-CELL XR 2.06.3”] to where the function replaces the line of data correctly.
I was hoping someone could point me in the right direction on how to properly integrate the str.replace function in my specific scenario, in order to get the data results I am looking for.

Thanks in advance.

How do I update the Play Billing in my Expo app?

I recently tried to publish a release for my app’s closed test in the google play console, however, I get this error:
“We’ve detected that an unsupported version of Play Billing is being used for this app. You must upgrade to version 5 or later of the Billing Library to publish this app. Find out more“.

This link talks about editing the build.gradle file, but I am developing my app without ejecting it, so I do not have android / iOS folders.

This is the android object in app.json:
enter image description here

may you help me with this?

Changing individual item in a array not resulting in expected output?

I’m changing idividual value in array and returning the entire array. Why does the return value show old values.

function capitalize(str) {
  const words = str.split(' ');
  for (let word of words) {
    word = word[0].toUpperCase() + word.slice(1);
    console.log(word);
  }

  return words.join(' ');
}
  • Input is a short sentence
  • Output is a short sentence
  • Expected output is A Short Sentence

Let me know what I’m missing? Thanks.

Is there a way to add an event listener to a text node?

For work I need to check if some text was clicked, then in the spot that was clicked append an ‘anchor’ for a sticky note. So I would like to add an event listener to the text node so that way the function will only run if text is clicked.

Th event listener is currently on the text nodes container which is causing issues if you click inside the container, but not on text nothing will happen. Is there a way to only add an event listener to the text or another work around to find out if text was clicked on?