What are the most important concepts to know in the following languages to land a job? [closed]

So I’ve been learning web development for a while, and I’m quite curious about what the most important concepts are that I should know in the following languages/frameworks (including HTML & CSS) to land a job:
HTML/CSS
Javascript
React
Node Js
Typescript

Basically, I want to know what the most important concepts are that interviewers look for.

NEXTJS redirect issue

"use server";
import { customFetch } from "./customFetch";
import { revalidatePath } from "next/cache";
import { BadRequestError } from "./ErrorHandler";
import uploadFileToS3 from "./uploadFileToS3";
import { redirect } from "next/navigation";

export const registerNewUser = async (prevState: any, formData: FormData) => {
  const image = formData.get("image") as File;
  if (!image) return;
  if (!["image/jpeg", "image/png"].includes(image.type.toLowerCase())) {
    throw new BadRequestError("Image type should be JPEG or PNG Only.");
  }
  if (image.size > 1024 * 1024 * 5) {
    throw new BadRequestError("Image size should not exceed 5MB.");
  }
  const buffer = Buffer.from(await image.arrayBuffer());
  const uploadedImage = await uploadFileToS3(buffer, image.name, image.type);
  const user = {
    firstName: formData.get("firstName") as string,
    lastName: formData.get("lastName") as string,
    password: formData.get("password") as string,
    confirmPassword: formData.get("confirmPassword") as string,
    email: formData.get("email") as string,
    image: uploadedImage,
  };
  try {
    const { data } = await customFetch.post("/api/auth/sign-up", user);
    revalidatePath("/");
    // redirect("/");
    return data;
  } catch (error: any) {
    console.log(error.response.data.error);
    return { message: error.response.data.error };
  }
};
import { connectDB } from "../../../../lib/mongoose";
import { User, userValidation, loginValidation } from "../../../../models/User";
import { BadRequestError } from "../../../../lib/ErrorHandler";
import asyncHandler from "../../../../lib/asyncHandler";
import { NextRequest, NextResponse } from "next/server";
import { S3 } from "@aws-sdk/client-s3";
import { redirect } from "next/navigation";

const s3 = new S3({
  region: process.env.AWS_REGION,
});

export const POST = asyncHandler(async (req: NextRequest) => {
  await connectDB(process.env.MONGODB_URI);
  const data = await req.json();
  const { error, value } = userValidation.validate(data);
  if (error) throw new BadRequestError(error.details[0].message);
  const isEmailExist = await User.findOne({ email: value.email });
  if (isEmailExist) {
    throw new BadRequestError("email is already exist");
  }

  const user = new User(value);
  await user.save();
  return NextResponse.json(
    {
      message: `Success Signing Up!`,
      success: true,
      user,
    },
    { status: 201 }
  );
});

I think this is one of the most easy solutions out there, but yet im stuck on it for a long time hehe.

I want to be able to redirect to the home page after signin up, I cant figure out how can i redirect to the home page and return data or nextreponse, cause when i redirect, the return statement is not accessible.

I shared 2 files cause im not sure even where to write the redirect logic.

thanks in advance.

Bootstrap, menu scrolls back to top after close menu

When i open my menu, and click on link, i scroll to down page with my menu, but when i close menu, I go back to the top of the page.

– Icon that open menu.

<a class="bi-list offcanvas-icon" data-bs-toggle="offcanvas" href="#offcanvasMenu" role="button" aria-controls="offcanvasMenu"></a> 

-** Menu**

<div class="offcanvas offcanvas-end" data-bs-scroll="true" tabindex="-1" id="offcanvasMenu" aria-labelledby="offcanvasMenuLabel">                
                <div class="offcanvas-header">                    
                    <button type="button" class="btn-close ms-auto" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                
                <div class="offcanvas-body d-flex flex-column justify-content-center align-items-center">
                    <nav>
                        <ul>
                            <li>
                                <a href="#contacts" >Контакти</a>
                            </li>
       </ul>
                    </nav>
                </div>
            </div>

**- section **

`<section class="contact-widget spad" id="contacts">lala </section>`

i TRY this script

`<script type="text/javascript">
    
    let y = window.scrollY;
    let offcanvas = document.getElementById('offcanvasMenu');
    offcanvas.addEventListener('hidden.bs.offcanvasMenu', (e) => {
       window.scrollTo(0, y);
    });
    
    </script> `

i try this script

`var myOffcanvas = document.getElementById('offcanvasNav')
myOffcanvas.addEventListener('hide.bs.offcanvas', function (e) {
    console.log(e)
    //e.preventDefault()
    //e.stopPropagation()
})

but nothing to help me.

this problem in `

How to properly use javascript within oTree / django?

I have a problem regarding implementing my non-oTree HTML, CSS, JS files into oTree format. I have this puzzle game (see screenshot 1) enter image description here. Implemented in oTree it is buggy – as you can see in screenshot 2 enter image description here. The JS logic kinda works as the counter recognises clicks on the here empty and buggy structured picture pieces. The JS code lies within the PuzzelPage.html file like this

{{ block scripts }}
<script> var turns = 0; // Zähler für die Anzahl der Züge
var puzzleSolved = false; // Zustand des Puzzles
var timer; // Globale Variable für den Timer
var currTile, otherTile; // Variablen für die aktuellen Puzzle-Teile

// Diese Funktion mischt ein Array in einer zufälligen Reihenfolge
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

// Diese Funktion wird aufgerufen, sobald das Fenster geladen ist
window.onload = function() {
    let imgOrder = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
    shuffleArray(imgOrder);

    // Erstelle die Puzzle-Teile und füge sie zum Board hinzu
    for (let r = 0; r < 3; r++) {
        for (let c = 0; c < 4; c++) {
            let tile = document.createElement("img");
            tile.id = r.toString() + "-" + c.toString();
            tile.src = imgOrder.shift() + ".jpg";
            tile.addEventListener("click", tileClick);
            document.getElementById("board").append(tile);
        }
    }

    // Starte den Timer
    startTimer();
};

function startTimer() {
    var timeLeft = 120; // 2 Minuten
    var timerElement = document.getElementById("timer");
    timer = setInterval(function() {
        var minutes = Math.floor(timeLeft / 60);
        var seconds = timeLeft % 60;
        timerElement.textContent = (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds;

        if (timeLeft <= 30) {
            timerElement.classList.add('time-warning');
        }

        if (timeLeft <= 0) {
            clearInterval(timer);
            timerElement.textContent = "00:00";
            alert("Die Zeit ist abgelaufen!");
            puzzleSolved = true;
            timerElement.classList.remove('time-warning');
        }

        timeLeft--;
    }, 1000);
}

function tileClick() {
    if (puzzleSolved) {
        return; // Keine Aktion, wenn das Puzzle bereits gelöst wurde
    }

    if (turns === 0) {
        currTile = this;
        turns++;
    } else {
        otherTile = this;
        let currImg = currTile.src;
        let otherImg = otherTile.src;
        currTile.src = otherImg;
        otherTile.src = currImg;
        turns = 0;

        let counter = parseInt(document.getElementById("counter").innerText);
        document.getElementById("counter").innerText = counter + 1;

        checkIfSolved();
    }
}

function checkIfSolved() {
    let tiles = document.getElementById("board").getElementsByTagName("img");
    for (let i = 0; i < tiles.length; i++) {
        let url = tiles[i].src;
        let match = url.match(/(d+).jpg$/);
        if (match && match[1]) {
            let number = parseInt(match[1], 10);
            if (number - 1 !== i) {
                return; // Nicht gelöst.
            }
        } else {
            return; // Nicht gelöst.
        }
    }
    
    puzzleSolved = true;
    clearInterval(timer);
    var timerElement = document.getElementById("timer");
    timerElement.textContent = "00:00";
    timerElement.classList.remove('time-warning');
    alert("Puzzle gelöst!"); // Benachrichtigung anzeigen
}<script> {{ endblock}}

also the picture file lie in the same file as the .html file.

If you maybe know why this is happening please let me now. If you need the code just let me know.

Kind regards 🙂

Problem comparing two dates in flight search engine

I want to write a condition that the day of the flight that someone choose is equal/ greatet than today:

heres the service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class FlightSelectionService {
  startingCity: string = 'Warsaw';
  selectedEndingCity: string = 'Paris';
  startingDate: Date = new Date();
  endingDate: Date = this.startingDate;
  currentDate: Date = new Date();
  adultsNumber: number = 0;
  childrenNumber: number = 0;
  validatePassengers(): boolean {
    const totalPassengers = this.adultsNumber + this.childrenNumber;
    return totalPassengers > 0;
  }

  validateDates(): boolean {
    
    console.log(this.startingDate + ' ' + this.startingDate.getTime());
    console.log(this.currentDate + ' ' + this.currentDate.getTime());
    console.log(this.startingDate.getTime() === this.currentDate.getTime());

    const isStartingDateValid =
      this.startingDate.getTime() >= this.currentDate.getTime();
    const isEndingDateValid = this.endingDate > this.startingDate;
    const areDatesDifferent =
      this.startingDate.getTime() !== this.endingDate.getTime();

    return isStartingDateValid && isEndingDateValid && areDatesDifferent;
  }
  constructor() {}
}

and the validation code inside valide Date function:

  console.log(this.startingDate + ' ' + this.startingDate.getTime());
    console.log(this.currentDate + ' ' + this.currentDate.getTime());
    console.log(this.startingDate.getTime() === this.currentDate.getTime());

    const isStartingDateValid =
      this.startingDate.getTime() >= this.currentDate.getTime();

it doesnt work, and i tried:

const startingDateInUTC = new Date(this.startingDate.getUTCFullYear(), this.startingDate.getUTCMonth(), this.startingDate.getUTCDate());
const currentDateInUTC = new Date(this.currentDate.getUTCFullYear(), this.currentDate.getUTCMonth(), this.currentDate.getUTCDate());

const isStartingDateValid = startingDateInUTC.getTime() >= currentDateInUTC.getTime();

How to implement this date comparsion correctly? The startingDate has to be currentDate or higher, so i can book flight for day or the future, not for the past.

Resource Name search on Project Online Resource Center PDP in Project Online

Resource Name search on Project Online Resource Center PDP in Project Online
Hi Team,

It seems like you’re trying to develop a JavaScript script to enable resource name search on Project Online Resource Center, but it’s not filtering the resources as expected

Here is the script:

`<!DOCTYPE html>
<html>
<head>
    <title>Resource Name Filter</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

    <script>
        $(document).ready(function () {
            // Fetch resource names and initialize autocomplete
            $.ajax({
                url: "<ProjectOnineURL>/_api/ProjectData/Resources",
                type: "GET",
                headers: {
                    "Accept": "application/json;odata=verbose"
                },
                success: function (data) {
                    var resources = data.d.results;
                    var resourceNames = resources.map(function(resource) {
                        return resource.Name;
                    });
                    // Initialize autocomplete
                    $("#resourceSearch").autocomplete({
                        source: resourceNames,
                        minLength: 1, // Minimum characters before autocomplete starts
                        select: function (event, ui) {
                            // Filter the web part based on selected resource name
                            filterWebPart(ui.item.value);
                        }
                    });
                },
                error: function (error) {
                    console.log("Error fetching resource names: " + JSON.stringify(error));
                }
            });

            // Function to filter the web part based on resource name
            function filterWebPart(resourceName) {
                try {
                    // Replace 'YourWebPartID' with the ID of your Project Online Resource Center web part
                    var webPart = document.getElementById('WebPartWPQ4');
                    if (webPart) {
                        // Set the filter criteria for the web part
                        webPart.set_filter(resourceName);
                        // Apply the filter
                        webPart.applyFilter();
                    } else {
                        console.log("Web part not found.");
                    }
                } catch (error) {
                    console.log("Error filtering web part: " + error);
                }
            }
        });
    </script>
</head>
<body>
    <label for="resourceSearch">Search Resource:</label>
    <input type="text" id="resourceSearch">
</body>
</html>`

How to test React Functional component context api with enzyme

Hi I am using react functional component and I have almost covered all the test cases which works fine until I added one line if code which uses the state value from my context api provider.

MyComponent code.

The line I added

  if (uploadedSuccessfullyContext) return null;

The existing function code

const fetchUserInfo = async () => {
 const userInfo = await getUserInfo();
 setEnterpriseId(userInfo.enterpriseId);
 setFirstName(userInfo.firstName);
 setIsLoading(false)
};



 return (
    <>rest of the component jsx<>               
    )

My test cases

jest.mock("react", () => ({
  ...jest.requireActual("react"),
  useContext: jest.fn()
}));

 const mockContextValue = {
    uploadedSuccessfullyContext: false
  };

  beforeEach(() => {
    setEnterpriseIdMock = jest.fn();
    setFirstNameMock = jest.fn();
    useContext.mockReturnValue(mockContextValue);
  });

it("should get userInfo and  call axios api correctly with no data", async () => {
    let wrapper;

    const mockUserInfo = {
      enterpriseId: "mockEnterpriseId",
      firstName: "mockFirstName"
    };

    getUserInfo.mockResolvedValue(mockUserInfo);

    const mockResponse = { data: [] };
    axios.get.mockImplementationOnce(() => Promise.resolve(mockResponse));

    await act(async () => {
      wrapper = mount(
        <DocumentHistory
          setEnterpriseId={setEnterpriseIdMock}
          setFirstName={setFirstNameMock}
        />
      );
    });
    expect(getUserInfo).toHaveBeenCalled();

    wrapper.update();
    expect(axios.get).toHaveBeenCalled();
    expect(axios.get).toHaveBeenCalledTimes(1);
  });

The error I am getting
TypeError: Cannot read properties of undefined (reading ‘get’)Jest

NOTE: If I remove that implementation of context api and if statement the testis passed and if add this is the error. Any idea what is missing ? your views and expertise are appreciated.

Transforming image in Vitest in Next.js codebase

Jest has a way to (not) process imported assets (.jpg, .png, …) by setting what should be the resolved value. So it can be a mock object:

jest.config.js

module.exports = {
  transform: {
    '\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/fileTransformer.js',
  },
};

As for Vite, I can’t find an equivalent option to do that. The reason I need to do it is that in our Next.js codebase, we have some dynamic require('../path/to/image')s in our pages which Next.js resolves to an object which contains, among other things, src property. But Vitest by default resolves such require by returning the content of the image, which in the test results into SyntaxError: Invalid or unexpected token (on the line of the require).

So is there a way to make Vite transform assets in particular way so that it conforms to Next’s image resolution mechanism?

React Native TVOS: force focus on any element after render

Is it possible to force focus on any element? I know I can do it using hasTVPreferredFocus prop, but it works only for the first time – while component is rendered. Is it possible to do something like that but without rerender? For example we are setting setTimeout and after 5 seconds focus switch programmatically from one element to another?

I’ve tried using hasTVPreferredFocus and rerender component but it has impact on performance.

react-hook-form validation with form POST i.e. not XHR

I have an existing react app that contains various forms, all using react-hook-form (v6) to validate the inputs prior to submission.

I’m creating a new form that also requires client side validation provided by react-hook-form, however, the form needs to work using a regular HTML for POST, i.e. not an XHR request, an actual POST to a url.

My issue is that the form validation never seems to run. As I said, I have a number of other forms all using react-hook-form that work just fine.

If anyone has come accross this same problem or has a solution it would be much appreciated. Thanks.

show thumbnails when selecting images in the file upload window

my page contains this code to select an image from a pc:

<input type="file" id="bc_imgItem" accept="image/*" onchange="imageUpload()">

when I do this, a window opens in which I see the images in a list. I need to see the thumbnails (previews) of the images. So that I can see what I want to upload. I hope there is a property in html that will do this.

I’m working on windows 11.
I have set up the explorer the right way. I see thumbnails of images when I open the directory, but it doesn’t work when I open the window for uploading these images to the site.

How to make calculation in javascript based on foreach at view form in Laravel

I want to create auto calculation in javascript but my form in foreach. So for now it only calculate once… But my form most of it is in array

here is my form view.blade code

<!-- Retail -->
                    <div class="card-body" id="retail">
                        @foreach($tenant->tenantSpace as $tenantSpace)
                        <div class="border p-2 mt-1 mb-3 mt-lg-0 rounded">
                            <h4>Lot no: {{$tenantSpace->space->unit_no}}</h4>
                            <input type="hidden" name="tenant_space_id[]" value="{{$tenantSpace->id}}">
                            <div class="row">
                                <div class="col-lg-3 mb-2">
                                    <div class="input-group">
                                        <div class="input-text text-muted" style="font-size: 17px; ">Total Size (Sqft): &nbsp;</div>
                                        <input id="total-area" name="total_area[]" class="form-control" type="number" placeholder="Total Size" value="{{ $tenantSpace->space->space_size }}" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-12">
                                <div class="row">
                                    <!-- First Table -->
                                    <div class="col-lg-4">
                                        <div class="col-lg-12">
                                            <div class="border p-2 mt-1 mt-lg-0 rounded">
                                                <h4>Year 1</h4>
                                                <div class="table-responsive">
                                                    <table>
                                                        <thead>
                                                            <tr class="text-muted mb-4 text-truncate">
                                                                <th>Price PSF (RM)</th>
                                                                <th style="padding-left: 9px;">Total Price (RM)</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody style="text-align: center;">
                                                            <tr>
                                                                <td>
                                                                    <input id="price-rate-yr1" name="price_rate_yr1[]" type="text" class="form-control" placeholder="Price PSF" value="{{ $tenantSpace->rate->price_rate_yr1 }}"></input>
                                                                    <input id="id" name="rate_id[]" type="hidden" class="form-control" placeholder="id" value="{{ $tenantSpace->rate->id }}"></input>
                                                                </td>
                                                                <td>
                                                                    <input id="monthly-rent-yr1" name="monthly_rent_yr1[]" type="text" class="form-control" placeholder="Total Price (RM)" value="{{ $tenantSpace->rate->monthly_rent_yr1 }}" readonly></input>
                                                                </td>
                                                                @error('price_rate_yr1[]')
                                                                <div class="alert alert-danger">{{ $message }}</div>
                                                                @enderror
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div> <!-- end .table-responsive-->
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-4">
                                        <div class="col-lg-12">
                                            <div class="border p-2 mt-1 mt-lg-0 rounded">
                                                <h4>Year 2</h4>
                                                <div class="table-responsive">
                                                    <table>
                                                        <thead>
                                                            <tr class="text-muted mb-4 text-truncate">
                                                                <th>Price PSF (RM)</th>
                                                                <th style="padding-left: 9px;">Total Price (RM)</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody style="text-align: center;">
                                                            <tr>
                                                                <td>
                                                                    <input id="price-rate-yr2" name="price_rate_yr2[]" type="text" class="form-control" placeholder="Price PSF" value="{{ $tenantSpace->rate->price_rate_yr2 }}"></input>
                                                                </td>
                                                                <td>
                                                                    <input id="monthly-rent-yr2" name="monthly_rent_yr2[]" type="text" class="form-control" placeholder="Total Price (RM)" value="{{ $tenantSpace->rate->monthly_rent_yr2 }}" readonly></input>
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div> <!-- end .table-responsive-->
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-4">
                                        <div class="col-lg-12">
                                            <div class="border p-2 mt-1 mt-lg-0 rounded">
                                                <h4>Year 3</h4>
                                                <div class="table-responsive">
                                                    <table>
                                                        <thead>
                                                            <tr class="text-muted mb-4 text-truncate">
                                                                <th>Price PSF (RM)</th>
                                                                <th style="padding-left: 9px;">Total Price (RM)</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody style="text-align: center;">
                                                            <tr>
                                                                <td>
                                                                    <input id="price-rate-yr3" name="price_rate_yr3[]" type="text" class="form-control" placeholder="Price PSF" value="{{ $tenantSpace->rate->price_rate_yr3 }}"></input>
                                                                </td>
                                                                <td>
                                                                    <input id="monthly-rent-yr3" name="monthly_rent_yr3[]" type="text" class="form-control" placeholder="Total Price (RM)" value="{{ $tenantSpace->rate->monthly_rent_yr3 }}" readonly></input>
                                                                </td>
                                                            </tr>

                                                        </tbody>
                                                    </table>
                                                </div> <!-- end .table-responsive-->
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                    <!-- end col -->

this is my current javascript for auto calculation

<script>
    $(document).ready(function() {
        // Function to calculate monthly rent for each year
        function calculateMonthlyRent(year) {
            var totalArea = parseFloat($('#total-area').val());
            var priceRate = parseFloat($('#price-rate-' + year).val());
            var monthlyRent = totalArea * priceRate;
            $('#monthly-rent-' + year).val(monthlyRent.toFixed(2));
        }

        // Bind input change event for each price input
        $('[id^=price-rate-]').on('input', function() {
            var year = $(this).attr('id').split('-').pop();
            calculateMonthlyRent(year);
        });

        // Trigger calculation initially
        $('[id^=price-rate-]').each(function() {
            var year = $(this).attr('id').split('-').pop();
            calculateMonthlyRent(year);
        });
    });
</script>

I expect it can auto calculate based on the array [], for now it can only auto calculate once … Please help me