Regex match dash optional flag

I’m trying to interpret user commands as dash optional flag.

{run -o -f -a file1 file2}

Something like this:

/{run (-o|-f) (w+) (.+?)}/g;

Is very limiting with only 1 choice of flag, how do I let them flag any amount, spit out the flags into groups, and not worry about a set amount of whitespace in between.

string = "{run    -a  file1 file2}"
string = "{run    -a -o -f  file1 file2}"
string = "{run -f-a-o  file1 file2}"

string.match(regex) should output each flag and each file name.

Play/Pause doesn’t work with useEffect and using setInterval

Here is my code. Whenever I play the start button, it spasms out. Any help would be appreciated! I’m wanting to, whenever I press the button, a timer for 1 second to count down based on the truthiness of isPlaying.

const [onBreak, setOnBreak] = useState(false) 
  const [isPlaying, setIsPlaying] = useState(false)

  useEffect(() => {
    const timerFunc = setInterval(() => {
    setIsPlaying(!isPlaying)
    if (!onBreak) {
      if (sessionSec === 0 && sessionMin !== 0) {
        setSessionSec(59)
        setSessionMin(sessionMin - 1)
      } else if (sessionSec !== 0 && sessionMin !== 0)  {
         setSessionSec(sessionSec - 1)
      } else if (sessionSec === 0 && sessionMin === 0) {
        setOnBreak(true)
      }
    } else if (onBreak) {
        if (breakSec === 0 && breakMin !== 0) {
        setBreakSec(59)
        setBreakMin(breakMin - 1)
      } else if (breakSec !== 0 && breakMin !== 0) {
         setBreakSec(breakSec - 1)
      } else if (breakSec === 0 && breakMin === 0) {
        setOnBreak(false)
      }
    } else {
  clearInterval(timerFunc)
  }
  }, 100);
  }, [isPlaying]);

    <button onClick={() => setIsPlaying(!isPlaying)}>{isPlaying ? 'Pause': 'Play'}</button>

Axios request returning undefined

So I have made a custom hook for fetching and I’m trying to use that hook and filter some stuff from it using my params. But the fetch returns undefined firstly which actually breaks my code.

Custom Hook code

import axios from "axios";
import { useState, useEffect } from "react"

export const useFetch = (url) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [error, setError] = useState('')


    const getData = () => {
        setLoading(true)
        try {
            axios.get(url)
                .then(response => {
                    setData(response.data);
                    setLoading(false)
                })
          } catch (error) {
            setError(error)
          }
    };

    useEffect(() => {
        getData()
    }, [url])

    return {loading, data, error}

}

Code where I’m trying to use the fetch

import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useFetch } from '../custom_hooks/useFetch';

const PersonDetails = () => {

    const { loading, data , error } = useFetch('https://randomuser.me/api?results=20');
    const { results } = data;
    const { id } = useParams();

    const [person, setPerson] = useState({})

    useEffect(() => { 
        const newPerson = results?.find(person => parseInt(person.login.uuid) === parseInt(id))
        console.log(newPerson)
        setPerson(newPerson)
    }, [])

    return (
        <div>
            Testing
        </div>
    )
}

export default PersonDetails

Mirage JS json data is console logging but not rendering on the page in React

I am working on a coding assessment and running into a problem when it comes to rendering dummy data from Mirage JS on my page. When I console log the data I’m looking for it shows up fine in the console but I can’t figure out why it’s not rendering on the page.

Here’s the server.js

import { createServer, Model } from "miragejs";
import faker from "faker";
import avatar from "./avatar.png";

export function makeServer({ environment = "test" } = {}) {
  let server = createServer({
    environment,
    models: {
      employee: Model,
    },
    seeds(server) {
      for (let i = 0; i < 10; i++) {
        server.create("employee", {
          id: faker.datatype.uuid(),
          firstName: faker.name.firstName(),
          lastName: faker.name.lastName(),
          email: faker.internet.email(),
          phone: faker.phone.phoneNumber(),
          bio: faker.lorem.paragraph(),
          avatar: avatar,
          address: {
            streetAddress: `${faker.address.streetAddress()} ${faker.address.streetName()}`,
            city: faker.address.city(),
            state: faker.address.stateAbbr(),
            zipCode: faker.address.zipCode(),
          },
        });
      }
    },
    routes() {
      this.namespace = "api";
      this.get(
        "/employees",
        (schema) => {
          return schema.employees.all();
        },
        { timing: 1000 }
      );
      this.patch(
        "/employees/:id",
        (schema, request) => {
          const attrs = JSON.parse(request.requestBody);
          const employee = schema.employees.find(request.params.id);
          employee.update(attrs);
        },
        { timing: 300 }
      );
      this.delete(
        "/employees/:id",
        (schema, request) => {
          const employee = schema.employees.find(request.params.id);
          employee.destroy();
          return new Response();
        },
        { timing: 300 }
      );
    },
  });
  return server;
}

and here’s the app.js

import { makeServer } from "./server";
import { useEffect, useState } from "react";

if (process.env.NODE_ENV === "development") {
  makeServer({ environment: "development" });
}

function App() {
  const [employees, setEmployees] = useState([])

  useEffect(() => {
    fetch('/api/employees')
    .then(res => res.json())
    .then(json => setEmployees(json.employees)
    )
  }, [])
  return (
    <div>
      <header>
        <h1>Employees</h1>
      </header>
      {employees.length > 0 ? (
        <table>
          <thead>
            <tr>
              <th>id</th>
              <th>first name</th>
              <th>last name</th>
            </tr>
          </thead>
          <tbody>
            {employees.map(({id, firstName, lastName}) => {
              <tr key={id}>
                <td>{id}</td>
                <td>{firstName}</td>
                <td>{lastName}</td>
              </tr>
          console.log(firstName)
            })}
          </tbody>
        </table>
      ) : (
        <p>No employees</p>
        )}
  </div>
  );
}
export default App;

Create a styling rule for clsx for React + Typescript

Having this clsx method which works fine:

const getLinkClasses = (disabled: boolean) => {
  return clsx('flex whitespace-nowrap', {
    'text-gray-500': !disabled,
    'text-gray-300 cursor-not-allowed': disabled
  });
};

There are two other optional variables, one for disabled and one for !disabled that are strings and can add new rules to the above method. Let’s call them disabledValue and notDisabledValue.

For example,

const disabledValue = 'bg-red-100'; 
const notDisabledValue = 'bg-green-100';

In order to add those variables, I’ve made the following changes:

export interface MyProps {
  disabledValue?: string;
  notDisabledValue?: string;
}

const getLinkClasses = (disabled: boolean, style: MyProps) => {
  const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
  const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;

  return clsx('flex whitespace-nowrap', {
    notDis: !disabled,
    dis: disabled
  });
};

The problem is that those two variables, notDis and dis aren’t read:

‘notDis’ is declared but its value is never read.ts(6133)

‘notDis’ is assigned a value but never
used.eslint@typescript-eslint/no-unused-vars

Is there a way to fix it?

Pass Javascript Array containing multiple files to PHP

I would like to send Javascript array containing files to PHP using AJAX

The following are 3 files that I want to send to the php side. (These outputs come from console.log(document.getElementById("id").files[0]);

File { name: "img1.svg", lastModified: 1641853737982, webkitRelativePath: "", size: 2506, type: "image/svg+xml" }
File { name: "img2.svg", lastModified: 1641853677323, webkitRelativePath: "", size: 1060, type: "image/svg+xml" }
File { name: "img3.svg", lastModified: 1641853656789, webkitRelativePath: "", size: 1845, type: "image/svg+xml" }

In this case there are 3 files (There can be more or less than that).

The 3 files are in a variable arrFiles.
So console.log(arrFiles) outputs:
Array [ File, File, File]

JQuery file

var form_data = new FormData();
var arrFiles = JSON.stringify(arrFiles)
form_data.append("imgs", arrFiles);

$.ajax({
    url:url,
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    success:function(data)
    {
        alert(data);
    }
}); 

php file

if(isset($_POST["imgs"])){
    //Would like to handle each image separately.
    $imgs = json_decode($_POST['imgs']);


    //May be something like :
    foreach($_POST["imgs"] as $img){
        $movePath = "images/".$img['name'];
        move_uploaded_file($img["tmp_name"], $movePath);
    }
    return;
}

Is there a way to handle this ?

Best way to Search ALL Terms in Array of Objects

I’m trying to filter out objects based on whether ALL the given search terms exist in SOME of the property values of EACH object in the array.
But I also don’t want to search within the deviceId property.

But is there a way to do it with less code?

So I do the following:

  1. Convert the objects into iterable arrays
  2. Filter out the array to remove arrays withdeviceId
  3. Convert the arrays back into the Key/Value pair objects
let DeviceDtoArrayOfArray = [];

DeviceDtos.forEach((indiv) => {
  DeviceDtoArrayOfArray.push(Object.entries(indiv));
});
let DeviceDtoArrayOfArrayFiltered = [];
DeviceDtoArrayOfArray.forEach((indiv) =>
  DeviceDtoArrayOfArrayFiltered.push(
    indiv.filter((indiv) => indiv[0] !== "deviceId")
  )
);

let DeviceDtoArrayOfArrayFilteredObjects = [];

DeviceDtoArrayOfArrayFiltered.forEach((indiv) => {
  DeviceDtoArrayOfArrayFilteredObjects.push(Object.fromEntries(indiv));
});
  1. Define sample search term array
  2. For each object from Step 3, create an array of it’s property values
  3. Filter each Object in the array by searching each Search Term, check to see if it exists within some of the property values from Step 5, if it exists, then the object is returned to a new array, if not, it’s filtered out

Sample Array containing the objects with deviceId

const DeviceDtos = [
  {
    deviceId: 1,
    deviceName: "Device0000",
    hwModelName: "Unassigned",
    deviceTypeName: "Unassigned",
    serviceTag: "A1A"
  },...

Sample Search Terms

const searchTerms = ["HwModel", "A1A"];

Filter out objects based on Search Terms

const results = DeviceDtoArrayOfArrayFilteredObjects.filter((indiv) => {
  const propertiesValues = Object.values(indiv); // all property values

  return searchTerms.every((term) =>
    propertiesValues.some(
      (property) => property.toLowerCase().indexOf(term.toLowerCase()) > -1
    )
  );
});

console.log(results);

SMTP mails going to spam folder

I am using JavaScript to automate sending emails on my website, with SMTP and a gmail email address however the emails are sent directly to the receivers spam folder. Is there a way around this?

Here is my code:

   function sendEmail() {

      Email.send({
        Host: "smtp.gmail.com",
        Username: "[email protected]",
        Password: "pass",
        To: document.getElementById('email').value,
        From: "[email protected]",
        Subject: "Subject",
        Body: "hooray",
      })
        .then(function (message) {
          alert("mail sent successfully")
        });
    }

Is there an efficient way to show images based on a route and file name using javascript?

Right now I have something like

const route = '/Images/Banner/'
const slides = [
  {
      name: "banner-01",
      url: `${route}banner-01.png`
  },
  {
      name: "banner-02",
      url: `${route}banner-02.png`
 
  },
  {
      name: "banner-03",
      url: `${route}banner-03.png`
  },
]
]

In this, I’m manually adding each image and it’s properties because there are only 3 images, but i want to dynamically add them based on the quantity of images with the same name (they’ll always are going to be named banner-NN).

Is there an efficient way to iterate through images with the same pattern of name (‘banner-‘) and place them in an array of objects?

rtl in material ui cause ruined my app appearance

i setuped mui rtl configuration step by step in v5mui. using emotion as styled-engine
stylis v4
stylis-plugin-rtl v2
every thing is ok but when using some complicated component my app apearance crash.
there are a warning in terminal that i think it will be the answere…
but i dont understand it.

enter code here

WARNING in ./node_modules/stylis-plugin-rtl/dist/stylis-rtl.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from '/home/hamid/Desktop/zahra/node_modules/stylis-plugin-rtl/src/stylis-rtl.ts' file: Error: ENOENT: no such file or directory, open '/home/hamid/Desktop/zahra/node_modules/stylis-plugin-rtl/src/stylis-rtl.ts' @ ./src/index.js 8:0-42 15:18-27