Always getting redirected to “/” on refresh from any route in app

So, everything works great I am redirected to homepage after login, the problem is when i refresh the page from any route i am always getting redirected to “/”, if i am in “/products” and refresh the page i m redirected to “/”

my App.js:

import Sidebar from "./components/sidebar/Sidebar";
import Topbar from "./components/topbar/Topbar";
import "./App.css";
import Home from "./pages/home/Home";
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
import UserList from "./pages/userList/UserList";
import User from "./pages/user/User";
import NewUser from "./pages/newUser/NewUser";
import ProductList from "./pages/productList/ProductList";
import Product from "./pages/product/Product";
import NewProduct from "./pages/newProduct/NewProduct";
import Login from "./pages/login/Login";
import { userRequest } from "./requestMethods";

function App() {

  const [admin, setAdmin] = useState(null)

  useEffect(() => {
    const verifyUser = async () => {
      try {
        const res = await userRequest.get('/verify')
        setAdmin(res.data)
      } catch (error) {
        console.log(error)
      }
    }
    verifyUser()
  }, [])

  return (
    <div>
    <Router>
      <Switch>
        <Route path="/login">
            {admin ? <Redirect to="/" /> : <Login/> }
          </Route>
      { admin !== null ? (
       <>
       <Topbar />
      <div className="container">
        <Sidebar />
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/users">
            <UserList />
          </Route>
          <Route path="/user/:userId">
            <User />
          </Route>
          <Route path="/newUser">
            <NewUser />
          </Route>
          <Route path="/products">
            <ProductList />
          </Route>
          <Route path="/product/:productId">
            <Product />
          </Route>
          <Route path="/newproduct">
            <NewProduct />
          </Route>
          
      </div> </>) : <Redirect to="/login"/>}
        </Switch>
    </Router>
    </div>
  );
}

export default App;

i try to use {admin !== null && (the routes here)} and it works but when i logout the application im not redirect to the login page “/login” and still in the page that i logged out.

can someone help me please?

Webpack is not compatible with react router dom v6?

Some hours ago, i posted a question about, why my routes weren’t working in my module-federation/react application, some people tried to help me, but they couldn’t.

I was using webpack so i can use microfronteds as components with react, and with TS, but, i had a big problem with my routes.

( This is the link to the post My routing with React router dom, <Route /> not working ).

Then i said, you know what, i’ll do this with pure JS, i’m pretty sure there was a problem with ts config or something like that.

Then, after migrating everything everything to simple JS, my routes with react-router-dom are not working as before.

Is there a posibility that, the new version of react-router-dom ( https://reactrouter.com/docs/en/v6/getting-started/overview ) and webpack do not match ? This sounds weird, but i don’t see other way to figure this out.

Recursion function in JavaScript

I have a simple recursion function that returns the sum of the first n elements of the array. I’m a little bit struggling with understanding: when the function calls itself through return return sum(arr, n-1) + arr[n-1]; what actually this sum(arr, n-1) does as it is not added to the final sum eventually and why it’s not been calculated.

Here’s the whole function, really appreciate any explanation.

    function sum(arr, n) {
if (n === 0) {return 0}
else if (n >= 1) {
  return sum(arr, n-1) + arr[n-1];
}
}

Javascript function return http response as null

While console.log("result ="+req.responseText); can output actual content, if(response == null) console.log("response null"); gets executed as well.
How can I return http response correctly?

var response = callSvc(textContent);
if(response == null) console.log("response null");

function callSvc(text){
var cleanUrl = "http://localhost:8080/api/mock";
var body={
    "text":text,
    "user":contentId
}
var contentId = generateContentId();
var req = new XMLHttpRequest();
    req.open("POST", cleanUrl);
    req.setRequestHeader("Content-Type", "application/json; charset=utf8");
    var json = JSON.stringify(body);
    req.send(json);
    req.onreadystatechange = function() {
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            var data = JSON.parse(req.responseText);
            console.log("result ="+req.responseText);
            return data;              
        } else {
            return error => {
                  console.error(error);
                }
        }
    }
}

Is there a way to use a fields value in the Model to set a style attribute dynamically?

I have created a CSHTML email template file to send alerts when a specific event is about to end (i.e. sends an alert 10-minutes before end, then at 5-minutes before end, etc.). I want to highlight the type of event (since there can be more than one) by color to differentiate the messages. What I currently have is this:

<strong style="color: {event color}">@alert.event</strong> is scheduled to end: <strong>@endEasternTime

I would like to be able to set the {event color} based on the value in @alert.event, but I’m not sure that I can. I tried to create a script in the file, but I’m not sure how to get its return value into the style tag:

<script>
    // Get the root element
    var r = document.querySelector(':root');

    // Create a function for getting a variable value
    function getEventColor(event) {
        // Get the styles (properties and values) for the root
        var rs = getComputedStyle(r);

        // Get the color associated with the event (default is the border color)
        return (event === "event1"
            ? rs.getPropertyValue('--evt1Color')
            : (event === "event2"
                ? rs.getPropertyValue('--evt2Color')
                : (event === "event3"
                    ? rs.getPropertyValue('--evt3Color')
                    : rs.getPropertyValue('--bdrColor')
                    )
                )
            );
    }
</script>

Note that I have created HTML variables in the file to match up the colors to other styles in the file (such as border-color) — for space considerations and clarity, I’m not going to show that here.

Is there a way to do this? If not using the inline CSS above, can I update a class or id on the fly using something like the script method above and, if so, what’s the best way. I appreciate any help.

Using a getter in array but getter won’t get the updated version (JAVA)

So basically I have this in one of my files:

public class Player {

private String[] PlayerWeaps;

public Player(){
    PlayerWeaps = new String[5];

}

public void addWeap(int index,String name){
    PlayerWeaps[index] = name;
}

public String[] getPlWeaps(){
    return this.PlayerWeaps;
}

And whenever I call it on my other file as

public class GM{
  private Player player; 
  public GM(){
   this.player = new Player();
   }

  public void run(){
   for(int i=0;i<5;i++){
    System.out.println("Weapons: " + player.getPlWeaps(i));  //this guy return's null
   }
  }
}

I also tried assigning player.getPlWeaps first but it doesn’t work too.

note: I’m self studying JAVA so I’m really not sure if theres something I have missed

How to get key from destructed object sweetalert2

Below code pops up a modal in the view that user select one of the options and then shows the selected option, I also need the id of selected option. e.g I need to get “4” if user select “John”. I am not sure how can I get it

        async function accept() {
            const { value: student } = await Swal.fire({
                input: 'select',
                width: 260,
                inputOptions: {
                    1: 'Peter',
                    2: 'Sam',
                    3: 'Tom',
                    4: 'John'
                },
                inputPlaceholder: 'Select student',
                showCancelButton: true,
            })
            if (student) {
                Swal.fire(`You selected: ${student}`)
                console.log('Id: ' ?????)
            }
        }

Format currency input field with dollar sign & commas

I have a revenue input field in a javascript/jquery form:

  1. Need a dollar sign :before
  2. add commas as the currency increases

I have a dollar sign showing via css, but issues centering it and ensuring the field entry point is next to it without overlapping. Unsure how to do the commas. Any suggestions or tips are welcome!

HTML:

  <form id="rev-calculator">
  <label for="price">Monthly Revenue</label>
  <div class="fields">
    <input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
    <br>
  </form>

CSS:

  <style>
      .body {
        text-align: left;
      }
      
      .fields {
        margin: 0 10px 0 0;
      }
      
      .fields:before {
        content: "$";
        text-align: center;
        position: relative;
        left:30px;
      }
      
      #price {
        border-radius: 5px;
        margin: 15px;
        padding: 10px;
        color: black;
      }
    </style>

JS:

<script>
  $('#rev-calculator').on('click', 'button', function(e) {
    e.preventDefault();
    var price = $("#price").val();
    console.log(price);
  })
</script>

codepen: https://codepen.io/kedarPE/pen/JjroYyb

input field

Typescript JSX with Generics – Parameter implicitly has an ‘any’ type

When using JSX syntax with Generics, Typescript is able to infer properties normally, except the type of function parameters.

Example code:

interface Dictionary {
  a: JSX.IntrinsicElements['a'];
  button: JSX.IntrinsicElements['button'];
}

type Props<T extends 'a' | 'button'> = Dictionary[T] & {
  as: T;
};

function Test<T extends 'a' | 'button'>(args: Props<T>) {
  return null;
}

<Test as="a" href="#" onClick={(arg) => {}} />; // Parameter 'arg' implicitly has an 'any' type.

Test({
  as: 'a',
  href: '#',
  onClick: (arg) => {}, // No error
});

TS Playground

If I place the mouse over the onClick property, it can tell the type of the onClick (React.MouseEventHandler<HTMLAnchorElement>), but still cannot infer the parameter’s type.

Tiny slider is tweaking at first image change and then go smooth. Thanks

like in topic, i have tiny slider who is tweaking at first change of image like 2 times and then go smooth and all is good, but first load gives tweak of try 2 change image.
Maybe u can figure it out? Really thanks for time, and i am fresh in webdev so dont be rude at me 😛

$(function() {
  const wrapper = $('#slider');

  setInterval(function() {
    const firstChild = $(wrapper).children()[0];
    $(firstChild)
      .fadeOut(1000)
      .next('a')
      .fadeIn(1000)
      .end()
      .appendTo('#slider');
  }, 3000);
});
img {
  max-width: 100%;
}

#slider:after {
  content: "";
  display: table;
  clear: both;
}

#slider img {
  float: left;
  margin: 0 -100% 0 0;
}

#slider {
  width: 200px;
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<figure id="slider">
  <a target="_blank" href="http://www.google.pl">
    <img src="https://i1.kwejk.pl/k/obrazki/2020/11/kwzgq1D7NOtJnNRp.jpg" />
  </a>
  <a target="_blank" href="http://www.google.pl">

    <img src="https://media.istockphoto.com/vectors/adorable-hedgehog-in-modern-flat-style-vector-vector-id930758362?k=20&m=930758362&s=612x612&w=0&h=UjgzuyypJq1tNI3RVKqlB1DjS1He72xtlw47DNWvFi8=" />
  </a>
  <a target="_blank" href="http://www.google.pl">

    <img src="https://img.redro.pl/plakaty/african-hedgehog-rolling-over-while-looking-at-camera-happy-400-195157167.jpg" />
  </a>
</figure>

Electron: Unable to load preload script: Resources/app.asar/src/preload.js

I have an electron app that builds and runs in development, but when packaging the app with electron-builder, the preload script is not packaged in the right location.

This is a well documented issue and there are very similar questions here and here for example, but none of the replies or solutions are working in my case.

From my electron.js file:

function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(app.getAppPath(), 'src/preload.js'),
            contextIsolation: true,
        },
    });

    // In production, set the initial browser path to the local bundle generated
    // by the Create React App build process.
    // In development, set it to localhost to allow live/hot-reloading.
    const appURL = app.isPackaged
        ? url.format({
            pathname: path.join(__dirname, 'index.html'),
            protocol: 'file:',
            slashes: true,
        })
        : 'http://localhost:3000';
    mainWindow.loadURL(appURL);

    mainWindow.webContents.openDevTools();
}

My preload script:

const { contextBridge, shell } = require('electron')

contextBridge.exposeInMainWorld(
    'electron',
    {
        openBrowserWindow: (url) => shell.openExternal(url)
    }
)

And my Electron app package.json:

    "build": {
        "extends": null,
        "appId": "com.app",
        "productName": "App",
        "directories": {
            "output": "dist"
        },
        "mac": {
            "target": {
                "target": "pkg",
                "arch": [
                    "universal"
                ]
            },
            "darkModeSupport": "true",
            "extendInfo": "app"
        },
        "pkg": {
            "installLocation": "/Applications",
            "overwriteAction": "upgrade"
        },
        "files": [
            "**",
            "../app/src/*",
            "src/preload.js"
        ],
        "extraResources": [
            "../app/src/*",
            "src/preload.js"
        ],
        "extraFiles": [
            "../app/src/*",
            "src/preload.js"
        ]
    }

Above I have tried to make sure the “src/preload.js” file is copied over in different ways, but I still get the error:

Unable to load preload script: …app/Contents/Resources/app.asar/src/preload.js

Error: Cannot find module ‘…app/Contents/Resources/app.asar/src/preload.js’

The preload script is in fact copied over, but it is not part of the app.asar file. It is copied in to a src folder outside of the Resources folder which contains the app.asar file:

enter image description here

How do I correctly configure electron-builder so this file is in the right location and can be accessed at package runtime?