Propagate yarn resolutions to other packages

I’m trying to create a “BOM” library that other projects can include, so that dependencies can be managed in a single place.

The BOM library includes a number of libraries, and I need to override some of their dependencies to resolve CVEs. However, I can’t figure out how to get those overrides to propagate through to the repos setting this BOM library as a dependency.

I’ve tried the following:

BOM:

"dependencies": {
  "libraryA": "1.0"
},
"resolutions": {
  "libraryB": "1.5"
}

Running yarn in the BOM repo correctly does not include the original version of libraryB, only the resolutions version.

However, adding BOM as a dependency to a repo and running yarn does not, and installs the original version of libraryB specified by libraryA.

If I instead specify the version I want as an explicit dependency:

BOM:

"dependencies": {
  "libraryA": "1.0",
  "libraryB": "1.5"
}

Then both versions of libraryB are included in the yarn.lock.

How can I force my repo to respect the resolutions specified in the BOM repo?

POST https://login.microsoftonline.com/xxxxxx/oauth2/v2.0/token 400 (Bad Request) – Msal – Microsoft graph

I’m trying to auth into my microsoft account with MSAL.

So this is my msalConfig :

    export const msalConfig = {
    auth: {  
      clientId: "xxx",
      authority: "https://login.microsoftonline.com/xxx", 
      redirectUri: "http://localhost:3000",
  

     },
    cache: {
      cacheLocation: "sessionStorage", // This configures where your cache will be stored
      storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
 
    },
   
  };
  
  // Add scopes here for ID token to be used at Microsoft identity platform endpoints.
  export const loginRequest = {
   scopes: ["User.Read"],

   };
  
  // Add the endpoints here for Microsoft Graph API services you'd like to use.
  export const graphConfig = {
      graphMeEndpoint: "https://graph.microsoft.com/v2.0/me",
 
   };

Here my graph file :

    import { graphConfig } from "./authConfig";

/**
 * Attaches a given access token to a Microsoft Graph API call. Returns information about the user
 */
export async function callMsGraph(accessToken) {
    const headers = new Headers();
    const bearer = `Bearer ${accessToken}`;

    headers.append("Authorization", bearer);

    const options = {
        method: "GET",
        headers: headers
    };

    return fetch(graphConfig.graphMeEndpoint, options)
        .then(response => response.json())
        .catch(error => console.log(error));
}

And here my request function

function RequestProfileData() {
    const request = {
        ...loginRequest,
        account: accounts[0], 
    };

    // Silently acquires an access token which is then attached to a request for Microsoft Graph data
    instance.acquireTokenSilent(request).then((response) => {
        callMsGraph(response.accessToken).then(response => setGraphData(response));
    }).catch((e) => {
        instance.acquireTokenPopup(request).then((response) => {
            callMsGraph(response.accessToken).then(response => setGraphData(response));
        });
    });
}

return (
    <>
        <h5 className="card-title">Welcome {name}</h5>
        {graphData ? 
            <ProfileData graphData={graphData} />
            :
            <Button variant="secondary" onClick={RequestProfileData}>Request Profile Information</Button>
        }
    </>
);

};

But when I’m trying to log, i get a bad request

 POST https://login.microsoftonline.com/xxxxxx/oauth2/v2.0/token 400 (Bad Request) - Msal - Microsoft graph

Does someone know why ?

I’ve seen that i maybe need to add “grand_type: authorization_code”.
But i don’t really know where to add it ( in my requestProfileData > request ? )

Thank you

Football Live Score

I’m doing a Live Score but the team names doesn’t show up on the score sheet. I’m using Visual Studio (JavaScript) and Localhost. I’m using a tutorial on this link -> https://doctorcodetutorial.blogspot.com/2020/09/make-football-live-scoreboard-app-with.html
My code:

var elapsedTime = document.querySelector("#elapsed");
var homeTeamLogo = document.querySelector("#homeLogo");
var homeTeamName = document.querySelector("#homeName");
var awayTeamLogo = document.querySelector("#awayLogo");
var awayTeamName = document.querySelector("#awayName");
var lastMatchGoals = document.querySelector("#goals");
var matchTable = document.querySelector("#matchTable");




function addMatchTile(data){

    var matchTile = document.createElement('div');
    matchTile.classList.add("match-tile");


    //home team box
    var homeTeam = document.createElement('div');
    homeTeam.classList.add("team");
    //logo and text-home
    var homeTileLogo = document.createElement('img');
    homeTileLogo.src = data['teams']['home']['logo'];
    var homeTileName = document.createElement('p');
    homeTeamName.innerHTML = data['teams']['home']['name'];

    homeTeam.appendChild(homeTileLogo);
    homeTeam.appendChild(homeTileName);

    //away team box
    var awayTeam = document.createElement('div');
    awayTeam.classList.add("team");
    //logo and text-away
    var awayTileLogo = document.createElement('img');
    awayTeamName.innerHTML = data['teams']['away']['name'];
    var awayTileName = document.createElement('p');
    awayTileLogo.src = data['teams']['away']['logo'];

    awayTeam.appendChild(awayTileLogo);
    awayTeam.appendChild(awayTileName);



    //Create score
    var score = document.createElement('p');
    score.innerHTML = data['goals']['home'] + "  -  "+ data['goals'] 
['away'];


    matchTile.appendChild(homeTeam);
    matchTile.appendChild(score);
    matchTile.appendChild(awayTeam);

    matchTable.appendChild(matchTile);
}



function getData(){

    fetch("https://api-football-v1.p.rapidapi.com/v3/fixtures?live=all", {
        "method" : "Get",
        "headers" : {
            "x-rapidapi-host": "api-football-v1.p.rapidapi.com",
            "x-rapidapi-key": "my key",
        }
    })
    .then(response => response.json().then(data => {
        var matchesList = data['response'];
        var fixture = matchesList[0]['fixture'];
        var goals = matchesList[0]['goals'];
        var teams = matchesList[0]['teams'];
        console.log(matchesList.length);
     //Now let's set our first match
        elapsedTime.innerHTML = fixture['status']['elapsed'] + "'";
        homeTeamLogo.src = teams['home']['logo'];
        homeTeamName.innerHTML = teams['home']['name'];
        awayTeamLogo.src = teams['away']['logo'];
        awayTeamName.innerHTML = teams['away']['name'];
        lastMatchGoals.innerHTML = goals['home']+ " - " + 
goals['away'];

    
        for(var i = 1; i<matchesList.length;i++){
            addMatchTile(matchesList[i]);
        }


    }))
     .catch(err => {
        console.log(err);
    });



}

getData();





   

Feature toggling using Expressjs middleware – frontend and backend

My current project is using Node for both frontend and backend and ExpressJS as the middleware.

I have a requirement where I need a feature toggling implementation to introduce some new features in my application. I am using a url parameter, e.g. &featureToggle=true to determine if the code of execution would be the new one or the existing.

Now I have parts in frontend and backend both which need to be changed based on the feature toggle. In the backend I can get the query object separately and extract the url param, similarly also in the frontend module.

Is there a way in which I can use Express to intercept the query param, set a variable value to either true or false based on the feature toggle, and which could be used across both the frontend and backend modules?

Grabbing content from a dictionary that is stored in a text file. [JavaScript]

I’m building a Pokemon team builder app. I want to click a button (which displays a Pokemons image so I know who it is) and have the data from a dictionary (image, name, moves, ability, etc.) displayed on the top div under the class “monster” (replacing the egg image). Just not sure where to get started.

html

<h2>Current Team</h2>
    <div id="your-team" class="team">
        <div class="slot">
            <div class="monster">
                <img src="egg.png" alt="">
            </div>
            <div class="info">
                <p>test</p>
            </div>
        </div>

    <h2>All Pokemon</h2>
    <div class="your-options" id="options">
        <div class="all-monsters" id="all">
            <ol class="list-pokemon">
                <li>
                    <button>
                        <img src="treecko.png" alt="">
                    </button>
                </li>

                <li>
                    <button>
                        <img src="grovyle.png" alt="">
                    </button>
                </li>

                <li>
                    <button>
                        <img src="sceptile.png" alt="">
                    </button>
                </li>
            </ol>
        </div>
    </div>

dictionary (stored in a separate text file)

let pokemon = {
    252: {
        "name": "Treecko",
        "type": "Grass",
        "ability": "Overgrow",
        "height": "1'08''",
        "weight": "11.0lbs",
        "location": "Starter Pokemon",
        "moves": {
            "Level --": "Pound",
            "Level --": "Leer",
            "Level 6": "Absorb",
            "Level 11": "Quick Attack",
            "Level 16": "Pursuit",
            "Level 21": "Screech",
            "Level 26": "Mega Drain",
            "Level 31": "Agility",
            "Level 36": "Slam",
            "Level 41": "Detect",
            "Level 46": "Giga Drain",
            "Level 50": "Energy Ball"
        },
    },
}

Nuxt plugin does not copy imported files to .nuxt

In a Nuxt project (version 2.14.9) I have a plugin file /plugins/ui-components.js that starts like this:

import UiList from '../components/UiList.vue'
import UiPageHeading from '../components/UiPageHeading.vue'
// more imports etc.

In nuxt.config.js I reference a file like this:

{
  // ...
  buildModules: [
    {
      handler: require('../lib/module.js'),
      options: {},
    },
  ],
}

Finally in ..lib/module.js I have

this.addPlugin({
    fileName: path.join(OUTPUT_DIR, 'plugins', 'ui-components.js'),
    src: path.resolve(__dirname, 'plugins/ui-components.js'),
    options: {
      registerDynamicComponentGlobally:
        options.registerDynamicComponentGlobally,
    },
  })

Now when I build or run the project ui-components.js gets copied to .nuxt, but not the .vue files that it imports. How can I fix this? My current workaround is to “manually” copy the files to .nuxt but of course I am looking for a better solution. Could it be that the plugin files need to be “stand-alone” meaning they are not allowed to import/require other dependencies?

Date showed when i click on a day Fullcalendar

I’m working on a Fullcalendar project.

I was wondering if there was a way, when a click on a day to add an event, to show on the modal directly the date clicked.

This is my modal: modal

I’m gonna explain myself better: this modal appeared when I click on a day. What i was wondering: if i click on (for example) 14 of April, is it possible to load on the Inizio (it means start in italian) datetime-local input to automatically add 14/02/2022 and maybe also the hour (like 08:00)?

drop down list with a button

In fact, I have a dropdown that filters records on an HTML table without a button.

The filter works perfectly without the button.

public selectedBrand: any;
public onChangeType(type: any) {
    this.selectedBrand = type;
    this.filteredCustomer = this.customerTransferts.filter(
        (item) => item.type === this.selectedBrand
    );
}

HTML

<select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeType($event)">
    <option [value]="'IN'">IN</option>
    <option [value]="'OUT'">OUT</option>
</select>

I just want to know how can I filter my records with a confirmation button please?

I think I just have to modify the HTML code?

I tried this but nothing works…. The filter no longer works with the confirmation button.

<select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand">
   <option [value]="'IN'">IN</option>
   <option [value]="'OUT'">OUT</option>
</select>
<button type="button" (click)="onChangeType($event)" class="btn btn-primary">Confirm</button>

Increse counter in Pig Game example

I’ve created a small project resembling the Pig Game. I wanted to add to the game the possibility of keeping track of how many games a player has won. It works fine with the first game, but when I click on the NEW GAME button and start a new game, the game won counter doesn’t increase and stays at 1, although the rest of the game works just fine.

Furthermore, I would like that when the score of 20 is reached, the game switches itself to “YOU WON” without me clicking on the holding button to pass the current score to the total score and win the game.

JAVASCRIPT CODE

// selecting elements
const player0El = document.querySelector('.player--0');
const player1El = document.querySelector('.player--1');

const score0El = document.querySelector('#score--0');
const score1El = document.getElementById('score--1');

const game0El = document.getElementById("games--0");
const game1El = document.getElementById("games--1");

const current0El = document.getElementById('current--0');
const current1El = document.getElementById('current--1');

const diceEl = document.querySelector('.dice');

const newShowEl = document.querySelector(".fa-flip");
const rulesShowEl = document.querySelector(".fa-shake");
const holdShowEl = document.querySelector(".fa-beat");
const rollShowEl = document.querySelector(".fa-spin");

const btnNew = document.querySelector('.btn-new');
const btnRoll = document.querySelector('.btn-roll');
const btnHold = document.querySelector('.btn-hold');

let scores, currentScore, activePlayer, games, playing;

// starting conditions
const init = function () {
  scores = [0, 0];
  currentScore = 0;
  activePlayer = 0;
  games = 0;
  playing = true;

  score0El.textContent = 0;
  score1El.textContent = 0;
  current0El.textContent = 0;
  current1El.textContent = 0;

  diceEl.classList.add('hidden');
  player0El.classList.remove('player--winner');
  player1El.classList.remove('player--winner');
  player0El.classList.add('player--active');
  player1El.classList.remove('player--active');
  document.getElementById(`name--${activePlayer}`).textContent = `PLAYER ${activePlayer === 0 ? "1" : "2"}`;

  btnRoll.removeAttribute("disabled");
  btnHold.removeAttribute("disabled");

  newShowEl.classList.remove("fa-flip");
  rulesShowEl.classList.add("fa-shake");
  rollShowEl.classList.add("fa-spin");
  holdShowEl.classList.remove("fa-beat");
};
init();

// switch player function
const switchPlayer = function () {
  document.getElementById(`current--${activePlayer}`).textContent = 0;
  currentScore = 0;
  activePlayer = activePlayer === 0 ? 1 : 0;
  player0El.classList.toggle('player--active');
  player1El.classList.toggle('player--active');
};

// rolling dice functionality
btnRoll.addEventListener('click', function () {
  newShowEl.classList.add("fa-flip");
  rulesShowEl.classList.remove("fa-shake");
  holdShowEl.classList.add("fa-beat");
  if (playing) {
    // generating a random dice roll
    const dice = Math.trunc(Math.random() * 6) + 1;
    // display the dice
    diceEl.classList.remove('hidden');
    diceEl.src = `images/dice-${dice}.png`;
    // check for rolled 1
    if (dice !== 1) {
      // add dice to current score
      currentScore += dice;
      document.getElementById(`current--${activePlayer}`).textContent = currentScore;
    } else {
      // switch to next player
      switchPlayer();
    }
  }
});

// holding dice functionality
btnHold.addEventListener('click', function () {
  if (playing) {
    // add current score to active player's score
    scores[activePlayer] += currentScore;
    document.getElementById(`score--${activePlayer}`).textContent = scores[activePlayer];
    // check if player's score is >= 100
    if (scores[activePlayer] >= 20) {
      // finish the game
      playing = false;
      diceEl.classList.add('hidden');
      document.querySelector(`.player--${activePlayer}`).classList.add('player--winner');
      document.querySelector(`.player--${activePlayer}`).classList.remove('player--active');
      document.getElementById(`name--${activePlayer}`).textContent = "You won!";
      newShowEl.classList.add("fa-flip");
      rollShowEl.classList.remove("fa-spin");
      holdShowEl.classList.remove("fa-beat");
      btnRoll.setAttribute("disabled", true);
      btnHold.setAttribute("disabled", true);
      current0El.textContent = 0;
      current1El.textContent = 0;
        if (activePlayer === 0) {
          games++;
          game0El.textContent = "Games won: " + games;
        } else if (activePlayer === 1) {
          games++;
          game1El.textContent = "Games won: " + games;
        }
    } else {
      // switch to the next player
      switchPlayer();
    }
  }
});

// refresh functionality
btnNew.addEventListener('click', init);

HTML CODE

<body>

  <div class="container-fluid">

    <main>
      <section id="left" class="player player--0 player--active">
        <h1 class="name" id="name--0">Player 1</h1>
        <h2 class="score" id="score--0">42</h2>
        <p id="games--0">Games won: 0</p>
        <div class="current rounded">
          <p class="current-label">Current</p>
          <p class="current-score" id="current--0">0</p>
        </div>
      </section>

      <section id="right" class="player player--1">
        <h1 class="name" id="name--1">Player 2</h1>
        <h2 class="score" id="score--1">72</h2>
        <p id="games--1">Games won: 0</p>
        <div class="current rounded">
          <p class="current-label">Current</p>
          <p class="current-score" id="current--1">0</p>
        </div>
      </section>

      <img src="images/dice-5.png" alt="Playing dice" class="dice img-fluid rounded" />
      <button class="btn btn-light btn-sm btn-new"><i class="fa-solid fa-circle-plus fa-flip"></i> New game</button>
      <button class="btn btn-light btn-sm btn-rules" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight"><i class="fa-solid fa-book-open fa-shake"></i> Rules</button>
      <button class="btn btn-light btn-sm btn-roll"><i class="fa-solid fa-arrows-rotate fa-spin"></i> Roll dice</button>
      <button class="btn btn-light btn-sm btn-hold"><i class="fa-solid fa-circle-arrow-down fa-beat"></i> Hold</button>

    </main>

    <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
      <div class="offcanvas-header">
        <h4 id="offcanvasRightLabel" class="offcanvas-title">Rules</h4>
        <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
      </div>
      <div class="offcanvas-body">
        <h5>You don't know how to play? Don't worry! Read the following instructions and have fun!</h5>
        <ul class="offcanvas-ul">
          <li>Roll the dice and <strong>add the number to your current score</strong>. You can either:</li>
          <ul>
            <li><strong>Keep rolling</strong>, adding new points to your current score</li>
            <li><strong>Hold</strong>, adding your points to your total score</li>
          </ul>
          <li>If you roll a <strong>one (1)</strong>, you lose all your current points</li>
          <li>Who first reaches <strong>100 points</strong>, wins the game</li>
        </ul>
      </div>
    </div>

  </div>

  <footer>
    <a href="https://www.facebook.com/people/Diana-DEstefano/100012558701947/" target="_blank"><i class="fa-brands fa-facebook-square footer-img"></i></a>
    <a href="https://www.instagram.com/destefanodiana99/?r=nametag" target="_blank"><i class="fa-brands fa-instagram-square footer-img"></i></a>
    <a href="https://www.linkedin.com/in/diana-d%E2%80%99estefano-118367174/" target="_blank"><i class="fa-brands fa-linkedin footer-img"></i></a>
    <a href="https://github.com/dlipianin" target="_blank"><i class="fa-brands fa-github-square footer-img"></i></a>
    <p class="p-footer">Diana D'Estefano. All rights reserved.</p>
  </footer>

  <script src="script.js" charset="utf-8"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>

Cards with read-more in bootstrap

I am using the following code to achieve a three-column design with a read more button. I changed the columns to display:flex to make them the same height. It looks fine when in default state. When you open a read-more option though, the other buttons shift too. Is there a possibility to prevent the buttons from shifting?

   <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
   
   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
   
   <!-- make cards same height -->
    <section id="cards" class="py-5 bg-white">
      <div class="container">
        <div class="row">
          <!-- diplay cards as flexbox, direction column and space between -->
          <div class="col-12 col-sm-4 d-flex flex-column justify-content-between">
            <!-- wrap text in a div -->
            <div>
              <h1>Shootings</h1>
              <p>Willkommen bei den ganzen tollen Elementen</p>
              <div class="collapse mb-3" id="collapseWidthExample1">
                This is some placeholder content for a horizontal collapse. It's hidden by default and shown when triggered.
              </div>
            </div>
            <!-- wrap button in a div -->
            <div>
              <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample1" aria-expanded="false" aria-controls="collapseWidthExample">Read more</button>
            </div>
          </div>
          <div class="col-12 col-sm-4 d-flex flex-column justify-content-between">
            <div>
              <h1>Shootings</h1>
              <p>Willkommen bei den ganzen tollen Elementen. Willkommen bei den ganzen tollen Elementen.</p>
              <div class="collapse mb-3" id="collapseWidthExample2">
                This is some placeholder content for a horizontal collapse. It's hidden by default and shown when triggered.
              </div>
            </div>
            <div>
              <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample2" aria-expanded="false" aria-controls="collapseWidthExample">Read more</button>
            </div>
          </div>
          <div class="col-12 col-sm-4 d-flex flex-column justify-content-between">
            <div>
              <h1>Shootings</h1>
              <p>Willkommen bei den ganzen tollen Elementen
              <div class="collapse mb-3" id="collapseWidthExample3">
                This is some placeholder content for a horizontal collapse. It's hidden by default and shown when triggered.
              </div>
              </p>
            </div>
            <div>
              <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample3" aria-expanded="false" aria-controls="collapseWidthExample">Read more</button>
            </div>
          </div>
        </div>
      </div>
    </section>

React doesn’t display initial state of UI on start

I’m building an E-commerce app with React and I stumbled on a problem that React doesn’t the UI render based the initial state when first start the page.

Problem description:

  • I have a sort state which has the initial state of "latest", based on this Sorting functionality – if sort has a value of "latest" – it will sort and return the newest items first.
  • But on start or when I refresh the page, the default value and state of sort will still be “latest” but the UI just display the oldest items first.
  • I have to click on other option and then choose the Latest option again for the sort logic to go through. When I refresh the page, the problem is back.
  • The logic for sorting other values works fine. In the demo below, you can see I log out the sort current state. On start, the sort value is already "latest".

-> What would be the case here that makes React not render the items based on initial state and how can we fix it?

Below is my code:

ProductList.jsx

const ProductList = () => {
  const location = useLocation()
  const category = location.pathname.split("/")[2]
  const [filters, setFilters] = useState({});
  const [sort, setSort] = useState("latest");

  // For Filters Bar
  const handleFilters = (e) => {
    const value = e.target.value
    // When choosing default value, show all products:
    if (value === "") {
      return setFilters([])
    } else {
      setFilters({
        ...filters,
        [e.target.name]: value,
      })
    }
  }

  return (
    <Container>
      <Navbar />
      <Announcement />
      <Title>Dresses</Title>
      <FilterContainer>
        <Filter>
          <FilterText>Filter Products: </FilterText>
          <Select name="color" onChange={handleFilters}>
            <Option value="">All Color</Option>
            <Option value="white">White</Option>
            <Option value="black">Black</Option>
            <Option value="brown">Brown</Option>
            <Option value="red">Red</Option>
            <Option value="blue">Blue</Option>
            <Option value="yellow">Yellow</Option>
            <Option value="green">Green</Option>
          </Select>
          <Select name="size" onChange={handleFilters}>
            <Option value="">All Size</Option>
            <Option>XS</Option>
            <Option>S</Option>
            <Option>M</Option>
            <Option>L</Option>
            <Option>XL</Option>
            <Option>36</Option>
            <Option>37</Option>
            <Option>38</Option>
            <Option>39</Option>
            <Option>40</Option>
            <Option>41</Option>
            <Option>42</Option>
            <Option>43</Option>
          </Select>
        </Filter>
        <Filter>
          <FilterText>Sort Products: </FilterText>
          <Select onChange={e => setSort(e.target.value)}>
            <Option value="latest">Latest</Option>
            <Option value="oldest">Oldest</Option>
            <Option value="asc">Price ↑ (Low to High)</Option>
            <Option value="desc">Price ↓ (High to Low)</Option>
          </Select>
        </Filter>
      </FilterContainer>
      <Products category={category} filters={filters} sort={sort} />
      <Newsletter />
      <Footer />
    </Container>
  );
}

Products.jsx

const Products = ({ category, filters, sort }) => {

  const [products, setProducts] = useState([])
  const [filteredProducts, setFilteredProducts] = useState([])

  useEffect(() => {
    const getProducts = async () => {
      try {
        const res = await axios.get( category 
          ? `http://localhost:5000/api/products?category=${category}` 
          : `http://localhost:5000/api/products`
        )

        setProducts(res.data)
      } catch (err) {
        console.log(`Fetch all items failed - ${err}`)
      }
    }
    getProducts()
  }, [category])

  useEffect(() => {
    category && setFilteredProducts(
      products.filter(item => 
        Object.entries(filters).every(([key, value]) => 
          item[key].includes(value)
        )
      )
    )
  }, [category, filters, products])

  // Sorting:
  useEffect(() => {
    console.log(sort)
    if (sort === "latest") {
      setFilteredProducts(prev =>
        [...prev].sort((a, b) => b.createdAt.localeCompare(a.createdAt))
      )
    } else if (sort === "asc") {
      setFilteredProducts(prev =>
        [...prev].sort((a, b) => a.price - b.price)
      )
    } else if (sort === "desc") {
      setFilteredProducts(prev =>
        [...prev].sort((a, b) => b.price - a.price)
      )
    } else {
      setFilteredProducts(prev =>
        [...prev].sort((a, b) => a.createdAt.localeCompare(b.createdAt))
      )
    }
  }, [sort])

  return (
    <Container>
      <Title>Popular In Store</Title>
      <ProductsWrapper>
        {filteredProducts.map(item => (
        <Product key={item._id} item={item} />
      ))}
      </ProductsWrapper>
    </Container>
  );
}

Demo:

demo gif

  • Explain demo: On start, it renders oldest items first. Have to choose another option and then return to the latest option for it to render. But in the console, the initial state of sort is already “latest” but it doesn’t match with the useEffect sorting logic.

Can i send data after each second (reactive) from WKWebView to native in Swift

I am creating a View which displays a local webpage which also has styles and JavaScript using a WKWebView.
I want to send data every second from WebView using node js like this

const timerEventEmitter = new EventEmitter();
timerEventEmitter.emit("update");
let currentTime = 0;
// This will trigger the update event each passing second
setInterval(() => {
    currentTime++;
    timerEventEmitter.emit('update', currentTime);
}, 1000);

timerEventEmitter.on('update', (time) => {
    console.log('Message Received from publisher');
    console.log(`${time} seconds passed since the program started`);
});

Can i send the log
{time} seconds passed since the program started
to native ios app, or send data using react like this

How to get @userName from @[userName] with the functionality of adding [] in the message with use of Regex?

I am working with react native and need to write down a message as @username and I am getting value from the API is @[userName]. I need to make it as I wanted with regex. I have tried and found a solution but it is also affecting to any of the square brackets [] I am adding to the message. It would be great if I can get help with this.