VueJS Style Guide – Coding Standard

I’m coming from PHP and Laravel and I know there is coding standard for different frameworks like PSR. However, when I searched the internet I can not find proper way to stylize my code or any standard. I know there is some style guides like Airbnb style guide but it is just a guide. I like to see how to chain, where to split the code, when it exceeds 120 chars or 80 chars, things like that.

I like to my code persistent and properly formatted. Do you have any recommendation about it?

How to use file option for each elements of list, and pass its value into controllers using jQuery

I am at beginner level for using Jquery.

Problem : so the problem is that, I have to add “choose file” for each of the element’s inside a tag. And display the image after selecting it inside the tag. But Has this is this list of elements using for each loop, it cannot different between the id property.
please see the images and code for reference and help me out,
Thank You !!!

[.cshtml]
@if (Model.DailyMenuProducts != null && Model.DailyMenuProducts.Count > 0)
{
@for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
 <li class="list-group-item">
    <input asp-for="@Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
    <label asp-for="@Model.DailyMenuProducts[i].ProductId">  @Model.DailyMenuProducts[i].ProductName</label>
    <input type="hidden" asp-for="@Model.DailyMenuProducts[i].ProductId"/>
    <input type="hidden" asp-for="@Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
        <div  class="uploadFile float-end">
            <label for="productImage">
                <img id="imageViewer" width="50" height="50" style="border: 1px solid #000000; cursor:pointer;" />
            </label>
            <input asp-for="@Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="@Model.DailyMenuProducts[i].ProductId" type="file" id="productImage" style="display:none; visibility:none" onchange="getImage(this.value);"/>
         </div>
</li>
}

[.js]

$(".uploadFile").on('change', function () {
        console.log('new file uploaded')
        //var array = $("#productImage").getIdArray();
        var file_data = $("#productImage").prop("files")[0];
        var files = event.target.files
        $("#imageViewer").attr("src", window.URL.createObjectURL(files[0]));
        var form_data = new FormData();
        var product_Id = (this.ProductId) ;
        var viewModel = { ProductId: product_Id, ProductImage: file_data};
        form_data.append("file", file_data);
        $.ajax({
            url: "/DailyMenuPlanner/AddPhoto",
            cache: false,
            contentType: false,
            processData: false,
            data: viewModel,
            type: 'post',
            success: function (result) {
                if (result.success == true) { alert("success!"); }
                else { alert("fail!"); }
            }
        });
        
    });

In this image you can see that each elements have choose file option, and i have selected image for the first one and so the image is reflecting there! but if i select image for 2nd element then it effect only for 1st element and image of 1st element will change not for the 2nd element

How to print “-1” if sudoku has no solution?

I have solved the sudoku using JavaScript but I want to print -1 if the given sudoku has no solution. I have done it using recursion and have exhausted all the ways that I could think of. Please help me solve this question for unsolvable sudoko’s.

let row = 0;
let col = 0;
let matrix = [
    [0, 4, 0, 0, 0, 0, 1, 7, 9],
    [0, 0, 2, 0, 0, 8, 0, 5, 4],
    [0, 0, 6, 0, 0, 5, 0, 0, 8],
    [0, 8, 0, 0, 7, 0, 9, 1, 0],
    [0, 5, 0, 0, 9, 0, 0, 3, 0],
    [0, 1, 9, 0, 6, 0, 0, 4, 0],
    [3, 0, 0, 4, 0, 0, 7, 0, 0],
    [5, 7, 0, 1, 0, 0, 2, 0, 0],
    [9, 2, 8, 0, 0, 0, 0, 6, 0]
];

function sudoku(matrix, row, col) {
    if (row == 9) {
        console.log(matrix);
        return;
    }

    let next_row = 0;
    let next_col = 0;
    if (col == 8) {
        next_col = 0;
        next_row = row + 1;
    }
    else {
        next_col = col + 1;
        next_row = row;
    }
    if (matrix[row][col] != 0) {
        sudoku(matrix, next_row, next_col);
    }
    else {
        for (let i = 0; i <= 9; i++) {
            if (isSafe(matrix, row, col, i) == true) {
                matrix[row][col] = i;

                sudoku(matrix, next_row, next_col);
                matrix[row][col] = 0;
            }
        }
    }
}

function isSafe(matrix, row, col, value) {

    for (let i = 0; i < matrix.length; i++) {
        if (matrix[i][col] == value) {
            return false;
        }
    }

    for (let i = 0; i < matrix.length; i++) {
        if (matrix[row][i] == value) {
            return false;
        }
    }

    let x = Math.floor(row / 3) * 3;
    let y = Math.floor(col / 3) * 3;

    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            if (matrix[x + i][y + j] == value) {
                return false;
            }
        }
    }
    return true;
}

sudoku(matrix, row, col);

Example of sudoku with no solution:

let matrix = [
    [0, 0, 0, 0, 5, 4, 3, 0, 6],
    [0, 0, 0, 0, 0, 3, 2, 7, 0],
    [0, 0, 0, 7, 2, 0, 0, 0, 1],
    [9, 0, 0, 0, 7, 0, 0, 5, 3],
    [0, 0, 0, 0, 0, 0, 0, 0, 0],
    [8, 2, 0, 0, 1, 0, 0, 0, 9],
    [3, 0, 0, 0, 6, 1, 0, 0, 0],
    [0, 4, 6, 9, 0, 0, 0, 0, 0],
    [7, 0, 1, 5, 4, 0, 0, 0, 6]
];

Possible async problem with firebase get request

I have a function useVenue that returns venue data from a call to firebase:

import { useState,useEffect } from 'react'
import { firebase } from './firebaseConfig'

export  function useVenues (){
  const [venues, setVenues] = useState([]);
  useEffect(() => {
    const venueArray = [];
    const getAllVenues = async () => {
      await firebase
        .firestore()
        .collection("venues")
        .get()
        .then((snapshot) => {
          snapshot.forEach((venue) => {
            venueArray.push(venue);
          });
          setVenues(venueArray);
        });
    };
    getAllVenues();
  }, []);

  const [...venueData] = venues.map((venue) => {
    
    const { 
      name, 
      photoUrl, 
      averageRating, 
      numRatings, 
      type,
      address,
      phone,
      website,
      reviews } = venue.data();

    return ({
      name: name,
      photoUrl: photoUrl,
      averageRating: averageRating,
      numRatings: numRatings,
      type: type,
      id: venue.id,
      reviews:reviews,
      address:address,
      phone:phone,
      website:website
    })
  });
  return {venueData}
};

This function is exported to venues.js where the venue data is destructured out and pass as props to MidSection.js:

venues.js

import { useParams } from 'react-router-dom';
import { useVenues } from '../useVenue';
import Header from '../components/Header'
import VenueDetails from '../components/venue-page/VenueDetails'
import MidSection from '../components/venue-page/MidSection';
import ReviewSection from '../components/venue-page/ReviewSection';

const Venue = () => {

    let {id} = useParams()
    const { venueData } = useVenues()

    const filteredVenue = venueData.filter(item => {
        return item.id === id
    })

    return(
        <div>
            <Header/>
            <VenueDetails filteredVenue = {filteredVenue}/>
            <MidSection filteredVenue = {filteredVenue}/>
            <ReviewSection filteredVenue = {filteredVenue} id = {id}/>
        </div>
    )
}

export default Venue

Lastly, in mid section I want to pull some information out of the venue data, passed as props as filteredvenue. I’m extracting this data with the following function:

import { useEffect,useState } from 'react'
import { convertToStars } from "../../helperFunctions";

const MidSection = ({ filteredVenue }) => {


  const extractRatings =   () => {
    const foodRatings = []
    filteredVenue[0].reviews.map((rating) => {
     foodRatings.push(rating.ratingFood)
    })
    return {foodRatings}
  }

  const {foodRatings} = extractRatings()

I logged out foodRatings and it returned the data I wanted. However when I refreshed the browser, the app crashed, giving the error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘reviews’)

I’m assuming this is some sort of asynchronous error and that the browser is rendering this component before the data has been returned. Unsure why this is happening since I’m using async/await in the initial firebase useVenues function, and the filteredVenue object is being mapped through elsewhere in this component with no problems. Suggestions?

Javascript- What is the difference between the thread pool and web API for handling asynchronous behavior?

Motive

For Javascript and node.js, I am trying to understand the difference between the thread pool and Web API.

What I Currently Understand

  • Thread pool: a multi-thread platform, where each thread executes their own operation.
  • Web API: an API built in to the browser. It is part of the event loop, along with the call stack and callback queue to enable asynchronous operations in Javascript.

What I Am Confused about

It seems like both the thread pool, and Web API, enable Javascript to handle asynchronous behavior.

When Javascript is executing code off the singly-threaded call stack, is it sent to the Web API, which uses a thread pool to create a single thread for each asynchronous operation?

If not, how does the Web API and thread pool work together to give Javascript asynchronous capabilities?

Calculate the required height for the right amount of scrolling

I’ve found this working example here: Use Vertical Scrollbar to Horizontal Scroll Content. It’s great except that I’d have to give a random height to #fakecontent. I’d like that when I scroll all the way down, I’d just arrive at the end of the horizontal slider. Not too far, not too close.

I tried to find the required ratio with no luck. with / height etc etc

How is finding the correct height of #fakecontent achievable?

$(window).on('scroll', function() {
  $("#realcontent").css("left", -$(window).scrollTop());
});
#realcontent {
  background-color: #333;
  position: fixed;
  top: 5px;
  left: 0;
  width: 2000px;
  color: #fff;
  height: 100px
}

#fakecontent {
  height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="realcontent">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam a est maiores fugiat nesciunt, at ad. Tempore odio velit ipsam, laborum explicabo repudiandae aliquid nostrum qui dolorem obcaecati, autem expedita!</div>
<div id="fakecontent"></div>

How to filter array to match params value with react

I wanted to create a e-commerce web application using react-bootstrap. I want the page to show different item based on category so if the URL is product/men’sclothing i want to filter my array and show only the product that have same category which is men’s clothing (my path: product/:category). I already tried to filter my array using .filter method but it didn’t work, it still show all product from various category, How can I fix it ?

Categorized product page:

const ProductList = () => {
  const { category } = useParams()
  const[productList, setProductList]= useState();

  useEffect(() =>{
    axios.get(`https://fakestoreapi.com/products`).then(res => {
        const products = res.data;
        setProductList(products);

        var filteredCategory =
         productList.filter((productList) =>productList.category === {category})
      })
  }, []);

  console.log(productList)

  return (
    <>
      <Row>
        <h1> This is {category} paged</h1>
        {productList && productList.map(product =>{
          const {id, title, price, category,description,image} = product;
          return(
          <Col lg={3} className="d-flex">
            <Card key={id} className="flex-fill productlist">
              <Card.Img variant="top" src={image} />
              <Card.Body>
                <Card.Title>{title}</Card.Title>
                <Card.Text>{category}</Card.Text>
                <Card.Text>
                  Current Price: {price}
                </Card.Text>
                <Button variant="primary">Add to cart</Button>
              </Card.Body>
            </Card>
          </Col>
          )
        })}
      </Row>
    </>
  )
}

export default ProductList

JSON.parse how to pass id?

How to pass id from categories to selected separated by comma ” [1,2,3] ” ? Thanks!

var categories = JSON.parse(document.querySelector("#company_category_select").dataset.categories)

$('#company_category_ids').comboTree({
  source: SelectJSONData,
  isMultiple: true,
  cascadeSelect: false,
  collapse: true,
  selectableLastNode: true,
  selected: [],  <-----------
});

Javascript Function Composition

I’m trying to understand behavior of function composition in javascript.

const Animal = (name) => {
  let properties = { name };
  return ({
    get name() { return properties.name },
    set name(newName) { properties.name = newName },
    breathe: function() {console.log(`${this.name} breathes!`); }
  })
}

const aquaticKind = (animal) => ({
  swim: () => console.log(`${animal.name} swims`)
})

const walkingKind = (animal, noOfLegs) => {
  const properties = { noOfLegs }
  return ({
    get noOfLegs() { return properties.noOfLegs },
    set noOfLegs(n) { properties.noOfLegs = n; },
    walk: () => console.log(`${animal.name} walks with ${properties.noOfLegs} legs`)
  })
}

const egglayingKind = (animal) => ({
  layEgg: () => console.log(`${animal.name} laid an egg`)
})

const Crocodile = (name) => {
  const info = Animal(name);
  return Object.assign(info,
                       walkingKind(info, 4),
                       aquaticKind(info),
                       egglayingKind(info)
                      );
}
const snooty = Crocodile('snooty');
snooty.breathe();
snooty.swim();
snooty.walk();
snooty.name = "coolie";
snooty.noOfLegs = 23 // I expected this to get update to 23
snooty.swim();
snooty.walk();
snooty.layEgg();

If you run the code above, you will see that noOfLegs never get updated, while name get updated. I can’t seem to wrap my head around this. How do we make noOfLegs get updated too?

Suggestions on how to create large scale plugin system nodejs?

I’m working on a project(built in node.js) which converts figma design to react source code and Currently we are building functionality where user can generate code with all the actions they integrated like navigation, API integration, firebase, supabase etc.

At initial level, it was super easy to handle with small actions like navigation (same page, different page, back navigation), where i just had to inject one line code into generated JSX page like below before return of JSX.

window.location.href="www.google.com"

But now it’s getting complicated where we need to handle more complex actions & also 3rd party integrations.

How can i define system in such a way that there’s no dependencies of actions with each other & easy to inject code of API integration or any other 3rd party libraries template.

I read one blog which had similar pattern, look at it here. But still wanted to know if there is any other solution or workaround available.

If not code example, any reference system would help also from github.

How to get props from with react router dom v6

I am trying to pass :id to url when i click a row of my table
trying using navigate("/edit/"+props); and onClick={() => handleClick(data.PacienteId)} but it didnt work then used useParams and created handleProceed to use it as onclick={handleProceed} but it still not working i just get url provided by Apiurl but /undefined

This is what i have in my routes

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" exact element={<Login  />} />
          <Route path="/dashboard" exact element={<Dashboard  />} />
          <Route path="/new" exact element={<Nuevo  />} />
          <Route path="/edit/:id" exact element={<Editar />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

This is my dashboard where i want to pass id to url clicking on table

export const Dashboard = (props) => {
  const [paciente, setPaciente] = useState([]);
  const {id}=useParams();
  const navigate = useNavigate();
  useEffect(() => {
    let url = `${Apiurl}pacientes?page=1`;
    axios.get(url).then((response) => {
      setPaciente(response.data);
    });
  }, []);

  const handleClick = (props) => {
    /* navigate("/edit/" + props); */
    navigate(`/edit/${id}`);
  };
  const handleProceed = (e) => {
    /* history.push(`/edit/${id}`); */
    navigate(`/edit/${id}`);
  };
  return (
    <>
      <Header />
      <div className="container">
        <table className="table table-dark table-hover">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">DNI</th>
              <th scope="col">NOMBRE</th>
              <th scope="col">TELEFONO</th>
              <th scope="col">CORREO</th>
            </tr>
          </thead>
          <tbody>
            {paciente.map((data, i) => {
              return (
                <tr key={i} /* onClick={handleProceed} */onClick={() => handleClick(data.PacienteId)}>
                  <td>{data.PacienteId}</td>
                  <td>{data.DNI}</td>
                  <td>{data.Nombre}</td>
                  <td>{data.Telefono}</td>
                  <td>{data.Correo}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

How to translate an element while avoiding flicker?

I’m having a list with a total of 5 elements and on hover, on any individual element, I’m trying to translate that element 7% in the x-direction and -15% in the y-direction with a half-second transition. It’s all working well till here.

Here is the code:

.listContainer{
    background-color:rgba(0,151, 19, 0.1);
    width: 70vw;
    margin: 0 auto;
    margin-top: 5vh;
    padding: 4vh;
}

.listItem{
    background-color:rgba(0,151, 19, 0.2);
    display: grid;
    grid-template-columns: 2fr 6fr 1fr;
    margin-top: 4vh;
    justify-content: row;
    transition: transform 0.5s;
}

.listItem:hover{
    transform : translate(7%, -15%);
    background-color: white;
}

.itemRank{
    text-align: center;
    color: rgb(183 225 188);
    /* border: 2px solid blue; */

}

.listHeading{
    text-align: center;
}

.listImg{
    border: 3px solid red;
}
<div class="listContainer">
        <div class="listHeading"><h1>Lorem, ipsum dolor.</h1></div>
        <div id="listItem1" class="listItem">
            <div class="listImg"></div>
            <div class="listText"><h2>this is item 1</h2></div>
            <div class="itemRank"><h2>#1</h2></div>
        </div>
        <div id="listItem2" class="listItem">
            <div class="listImg"></div>
            <div class="listText"><h2>this is heading 2</h2></div>
            <div class="itemRank"><h2>#2</h2></div>
        </div>
        <div id="listItem3" class="listItem">
            <div class="listImg"></div>
            <div class="listText"><h2>this is heading 3</h2></div>
            <div class="itemRank"><h2>#3</h2></div>
        </div>
        <div id="listItem4" class="listItem">
            <div class="listImg"></div>
            <div class="listText"><h2>this is heading 4</h2></div>
            <div class="itemRank"><h2>#4</h2></div>
        </div>
        <div id="listItem5" class="listItem">
            <div class="listImg"></div>
            <div class="listText"><h2>this is heading 5</h2></div>
            <div class="itemRank"><h2>#5</h2></div>
        </div>
    </div>

enter image description here

But here the problem is, Let’s say you hovered between that first 7% of the element in the x-direction as shown in the image, then the element translates 7% in the x direction and leaves the hovered area and that’s why tries to come back to its original position but it again comes in the hovered area and that’s why again translates and leaves the hovered area that’s why again come back and that’s how it goes in a continuous to and forth motion. So, what can I do to solve this…?