Why does my code behave differently in .map function?

i have this code:

  const [cart, setCart]=useState([{}]);

  function AddToCart(item){
    setCart((prevItem)=>{
      if (prevItem.find(cartItem => cartItem.productId ===item.productId)){
        console.log('yes')
        let objIndex= prevItem.findIndex(stuff => stuff.productId ===item.productId)
        prevItem[objIndex].quantity = (prevItem[objIndex].quantity +1)
        return [...prevItem]

      }
      console.log('no');
      return [...prevItem, item];
              
  })
}

It behaves exactly as I need it to when I call it, everytime I click, the same item stays the same in array but the quantity increases

 const Item = {
    productId: 8,
    name:'Kettle', 
    price: 10
  };

When i render: 
<button onClick={() => AddToCart(Item, Item.quantity=1)} >test</button>

But when I use the same code in a .map function with all the items, I notice the quantity never goes above 2 and I cannot add additional items to get the quantity to increase:

{shopData.map((data, index) => (
      <div className='grid-item-1'>
      <Card style={{ width: '18rem' }} key={data.index}>
      <Card.Img variant="top" src={data.imageUrl} />
      <Card.Body>
        <Card.Text className='card-title'>
          {data.name}
        </Card.Text>
        <Card.Text className='card-price'>
        {data.price}
        </Card.Text>
        <button className='add-cart-btn' >Add to Cart </button>
        <button onClick={() => AddToCart(data, data.quantity=1)}  className='add-item-btn' >Add Items </button>
        
      </Card.Body>
      </Card>
      </div>
         ))}

Can someone explain why this is the case?

I created the function and used it to increment quantity, which works completely fine. Using it in a .map function however, quantity never goes above 2.

how we can upload image can we stored on another server in php

Warning: ftp_put(Census Logo Final.png): Failed to open stream: No such file or directory in C:xampphtdocsuploadonserverftp_upload.php on line 30
Error uploading file! Please try again later.

I want that I have a form on my server, in that I have uploaded a file, written jpg nad pdf and submit it, then it should be stored on another server in php.

Warning: ftp_put(Census Logo Final.png): Failed to open stream: No such file or directory in C:xampphtdocsuploadonserverftp_upload.php on line 30
Error uploading file! Please try again later.

How can I correctly resize all plotly plots encapsulated in a javascript tab?

I am new to handling html objects from R and I am having an issue while trying to create html tabs from named lists (the target document is html pages obtained from RMarkdown). Long story short, while I am able to create the tabs that I want using htmltools and shiny tags, I can’t manage to have all plotly plots correctly resized to their pane width. By this I mean that the first plot in the first pane (that is display by default at opening) is having the correct size as shown below :
Plotly plot correctly resized

While plots in others tabs appear shrunk:
Plotly plot in the second tab

I have been able to minimise the code required to reproduce my issue. I rely on the following project for creating the tabs : tabbis.js. It works by declaring tabs name in custom tags div data-tabs and panes content in custom tags div data-panes; then the script is handling everything.

Code to reproduce :

library(htmtools)
library(rlang)
library(plotly)

div_tabs <- function (..., .noWS = NULL, .renderHook = NULL)
{
  contents <- dots_list(...)
  tag("div data-tabs", contents, .noWS = .noWS, .renderHook = .renderHook)
}

div_panes <- function (..., .noWS = NULL, .renderHook = NULL)
{
  contents <- dots_list(...)
  tag("div data-panes", contents, .noWS = .noWS, .renderHook = .renderHook)
}

fig <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
fig2 <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
fig3 <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")

css <- readLines("https://raw.githubusercontent.com/paulthewalton/tabbisjs/main/assets/css/dist/style-default.min.css")

tabbis <- readLines("https://raw.githubusercontent.com/paulthewalton/tabbisjs/main/assets/js/dist/tabbis.es6.min.js")

T <- browsable(
  tagList(
    tags$html(
      tags$head(
        htmltools::tags$style(htmltools::HTML(css))
      ),
      tags$body(
        div_tabs(
          tags$button("Tab1"),
          tags$button("Tab2"),
          tags$button("Tab3")
        ),
        div_panes(
          tags$div(fig),
          tags$div(fig2),
          tags$div(fig3)
        )
      ),
      tags$script(htmltools::HTML(tabbis)),
      tags$script(htmltools::HTML("tabbis();"))
    )
  )
)
save_html(T,"error_tabbis.html")

To fix this I am trying to call a function as in A similar example using materializeR but with dygraph. But I have been unable to find the correct function for plotly (To be honest I don’t fully understand the proposed fix)

I have done so by adding :

tags$script(
"
$(document).ready(function(){
  $('div data-tabs').on('click', function(evt) {
    console.log('resizing');
    HTMLWidgets.find('.pyplot').resize();
  })
});
")

at the end of the tagList.

If you have any tips or idea to handle this issue (or better way to have html panes in RMarkdown if any) I would truly appreciate it! Thanks for reading.

Cyclical array in JS

I recently read about cyclical array and as far as I understood, it is when we put array in itself. Also, if we then iterate over the cyclical array then we can face infinite loop. Thus, I created this code:

const array = [1, 2, 3];
array.push(array); // Creating a cyclic reference

for (let i = 0; i < array.length; i++) {
  array[i];
}

I executed the above code but no infinite loop was faced. Did I miss something?

How to load html.DropdownList to the table from Javascript

In my asp.net MVC application, Im trying to create a purchase order view with item adding button.

So for the first <-td> tag I want to show the dropdown list and other columns with input text fields.

Then the Rows are added to the table using javascript.

Want to know how to add same input with the current styles (td width and class) from the javascript.

This is my current code

HTML

<tbody class="table-border-bottom-0">
   <tr id="tablerow0">
     <td>
       <strong> 1</strong>
     </td>
     <td width="40%"> @Html.DropDownList("Item_ID", null, "--Select the Item--", htmlAttributes: new { @class = "form-select", @Id = "Company", oninvalid = "this.setCustomValidity('Select the Item')", oninput = "this.setCustomValidity('')", name = "Item_Id[0]" }) @* <input name="Item_Id[0]" type="text" value="" required="required" class="form-control" />*@ </td>
     <td width="10%">
       <input name="AdditionalComments[0]" type="text" value="" required="required" class="form-control" />
     </td>
     <td width="10%">
       <input name="AcidStables[0]" type="text" value="" class="form-control" />
     </td>
     <td width="20%">
       <input name="AcidStables[0]" type="text" value="" class="form-control" />
     </td>
     <td width="20%">
       <input name="AcidStables[0]" type="text" value="" class="form-control" />
     </td>
     <td>
       <button type="button" class="btn btn-danger" onclick="removeTr(0);">x</button>
     </td>
   </tr>
 </tbody>

<p>
   <button id="add" type="button" class="btn btn-primary">Add</button>
</p>

Javascript

var counter = 2;
$(function () {
  $('#add').click(function () {
    $('<tr id="tablerow' + counter + '"> ' +
      '<td >' +
      '<label id="CountItems" > <strong>' + counter + '</strong> </label> </td>' +
      '<td width="40%">' +
      '<input type="text" class="text-box single-line"  name="Item_Id[' + counter + ']" value="" required="required"  />' +
      '</td>' +

      '<td width="10%">' +
      '<input type="text" class="text-box single-line"  name="AcidStables[' + counter + ']" value="" required="required" />' +
      '</td>' +
      '<td width="10%">' +
      '<input type="text" class="text-box single-line"  name="AcidStables[' + counter + ']" value="" required="required" />' +
      '</td>' +
      '<td width="20%">' +
      '<input type="text" class="text-box single-line"  name="AcidStables[' + counter + ']" value="" required="required" />' +
      '</td>' +
      '<td width="20%">' +
      '<input type="text" class="text-box single-line"  name="AcidStables[' + counter + ']" value="" required="required" />' +
      '</td>' +
      '<td>' +
      '<button type="button" class="btn btn-danger" onclick="removeTr(' + counter + ');">x</button>' +
      '</td>' +
      '</tr>').appendTo('#submissionTable');
    counter++;
    return false;
  });
});

function removeTr(index) {
  if (counter > 1) {
    $('#tablerow' + index).remove();
    counter--;
  }
  return false;
}

This is how the current view looks

Before clicking on the Add Button

enter image description here

After clicking to the Add Button

enter image description here

multiple flip cards with two button

I have multiple stack of cards with two button one to flip the current ( top) car and the second to add a fallen effect class
could not the button to work
please help

  const cards = document.querySelectorAll(".card")

    const flipBtn=document.querySelectorAll('.fliping')
    flipBtn.forEach(function(item){
        item.addEventListener('click',function(){

            // cards.forEach(function(card){
            //   this.classList.toggle('flipcard')
            // })
        })

    })

    document.querySelectorAll('.delete').forEach(function(item) {
  item.addEventListener('click', function(e) {
    // console.log("jjjj")
    // let newClass = this.getAttribute('data-delete');
    // let getParent = parent(this, '.item', 1);
    // console.log(getParent)
    cards.classList.add('fall');

  });
}); 
 const cards = document.querySelectorAll(".card")

    const flipBtn=document.querySelectorAll('.fliping')
    flipBtn.forEach(function(item){
        item.addEventListener('click',function(){

            // cards.forEach(function(card){
            //   this.classList.toggle('flipcard')
            // })
        })

    })

    document.querySelectorAll('.delete').forEach(function(item) {
     item.addEventListener('click', function(e) {
    // console.log("jjjj")
    // let newClass = this.getAttribute('data-delete');
    // let getParent = parent(this, '.item', 1);
    // console.log(getParent)
    cards.classList.add('fall');

  });
});

could not get the buttons to work

Animating alternating circles on canvas with gsap + scrolltrigger

https://codepen.io/handiworknyc/pen/GRYLjeE

Hi all, thanks in advance for your help.

I’ve never really used canvas before but i got pretty far with ChatGPT…

However ChatGPT was not good at getting these to animate with gsap.

How can I set it up so that these circles animate (i’m thinking a staggered fade in, the first row from the left and the second row from the right) when the canvas element scrolls into view using ScrollTrigger

var HW = {};

var $$ = function (selector, parent) {
    return Array.prototype.slice.call((parent ? parent : document).querySelectorAll(selector));
};


var loop = function (arr, callback, method) {
    method = method || 'forEach';
    return Array.prototype[method].call(arr, callback);
};

HW.circMotif = function(canvas) {            
            const ctx = canvas.getContext('2d');
            const circleSize = 80; // Size of the circles
            const padding = 3; // Padding between circle and square
            
            const canvasWidth = window.innerWidth + 6;
            const numRows = 2; // Number of rows
            
            // Calculate the square size based on the available width and padding
            const squareSize = (canvasWidth - 2 * padding) / Math.ceil(canvasWidth / (circleSize + 2 * padding));
            
            // Calculate the number of circles that can fit in a row
            const numCirclesPerRow = Math.floor(canvasWidth / squareSize);
            
            // Calculate the total width of the circles and padding
            const totalWidth = numCirclesPerRow * squareSize;
            
            // Calculate the left margin to center the circles
            const marginLeft = (canvasWidth - totalWidth) / 2;
            
            // Calculate the canvas height based on the number of rows
            const canvasHeight = numRows * squareSize;
            
            // Set the canvas dimensions
            canvas.width = canvasWidth;
            canvas.height = canvasHeight;
            
            // Clear the canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // Loop through the rows and columns to draw the circles
            for (let row = 0; row < numRows; row++) {
                for (let col = 0; col < numCirclesPerRow; col++) {
                    // Calculate the x and y coordinates for the current circle
                    const x = marginLeft + col * squareSize;
                    const y = row * squareSize;
            
                    // Determine the starting color combination for each row
                    const isBlueCircle = ((row + col) % 2 === 0);
            
                    // Set the fill color and draw the square
                    ctx.fillStyle = (isBlueCircle) ? 'blue' : 'white';
                    ctx.fillRect(x, y, squareSize, squareSize);
            
                    // Draw the circle
                    ctx.beginPath();
                    ctx.arc(x + squareSize / 2, y + squareSize / 2, circleSize / 2, 0, 2 * Math.PI);
                    ctx.fillStyle = (isBlueCircle) ? 'white' : 'blue';
                    ctx.fill();
                }
            }
        }            
        
        HW.doCircMotif = function() {
            var $circleZazz = $$('.circle-zazz');
            
            loop($circleZazz, function(el){
               HW.circMotif(el);
            })
            
        }

            
            HW.doCircMotif();

The thumbnail won’t preview a video when hovering

I’m working on a personal project, and I have a thumbnail which I want to play a YouTube video when I hover for 2 seconds also when hovering over the thumbnails there should be a black opacity layer that covers the thumbnail and the title of the videos should be fade in. when clicking on the thumbnail a lightbox should open.
It seems a lot but I’m just practicing, but the code isn’t working.

Here’s the code

Html

<section class="container photo">
        <div class="thumbnails">
         <div class="thumbnail" data-video-id="D9N7QaIOkG8">  <!-- Put the youtube id in the data-video-id slot to show the video -->
            <img src="assetsmeyra.jpg" alt="Thumbnail 1">
            <div class="video-overlay">
              <div class="title">Video Title 1</div>
              <div class="lightbox">
                <iframe src="" frameborder="0" allowfullscreen></iframe>
              </div>
            </div>
          </div>
          
          <div class="thumbnail" data-video-id="D9N7QaIOkG8"> <!-- Put the youtube id in the data-video-id slot to show the video -->
            <img src="assetsNouvelle.jpg" alt="Thumbnail 2">
            <div class="video-overlay">
              <div class="title">Video Title 1</div>
              <div class="lightbox">
                <iframe src="" frameborder="0" allowfullscreen></iframe>
              </div>
            </div>
          </div>
          
          <div class="thumbnail" data-video-id="D9N7QaIOkG8">  <!-- Put the youtube id in the data-video-id slot to show the video -->
            <img src="assetsBASF.jpg" alt="Thumbnail 3">
            <div class="video-overlay">
              <div class="title">Video Title 1</div>
              <div class="lightbox">
                <iframe src="" frameborder="0" allowfullscreen></iframe>
              </div>
            </div>
          </div>
          
          <div class="thumbnail" data-video-id="D9N7QaIOkG8">  <!-- Put the youtube id in the data-video-id slot to show the video -->
            <img src="assetsvalmet.jpg" alt="Thumbnail 4">
            <div class="video-overlay">
              <div class="title">Video Title 1</div>
              <div class="lightbox">
                <iframe src="" frameborder="0" allowfullscreen></iframe>
              </div>
            </div>
          </div>
          
          <div class="thumbnail" data-video-id="D9N7QaIOkG8"> <!-- Put the youtube id in the data-video-id slot to show the video -->
            <img src="assetssbb.jpg"  alt="Thumbnail 5">
            <div class="video-overlay">
              <div class="title">Video Title 1</div>
              <div class="lightbox">
                <iframe src="" frameborder="0" allowfullscreen></iframe>
              </div>
            </div>
          </div>
          
          <div class="thumbnail" data-video-id="D9N7QaIOkG8"> <!-- Put the youtube id in the data-video-id slot to show the video -->
            <img src="assetsHertz.jpg" alt="Thumbnail 6">
            <div class="video-overlay">
              <div class="title">Video Title 1</div>
              <div class="lightbox">
                <iframe src="" frameborder="0" allowfullscreen></iframe>
              </div>
            </div>
          </div>

Css

.container.photo {
  border-bottom: 1px solid var(--special-color);
  margin-bottom: 20px;
  padding: 50px 0px;
}

.thumbnails {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
}

.thumbnail {
  position: relative;
  width: 45%;
  height: auto;
  margin-top: 50px;
  overflow: hidden;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: none;
  background: rgba(0, 0, 0, 0.8);
  z-index: 1;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.thumbnail.hovered .video-overlay {
  opacity: 1;
}

.video-overlay iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
}

.title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.lightbox {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  z-index: 999;
  justify-content: center;
  align-items: center;
}

.lightbox.active {
  display: flex;
}

.lightbox iframe {
  width: 800px;
  height: 450px;
}

Javascript

function onYouTubeIframeAPIReady() {
  const thumbnails = document.querySelectorAll(".thumbnail");
  const players = [];

  thumbnails.forEach(function(thumbnail) {
    const videoOverlay = thumbnail.querySelector(".video-overlay");
    const videoId = thumbnail.dataset.videoId;
    let player;
    let hoverTimer;

    thumbnail.addEventListener("mouseenter", function() {
      hoverTimer = setTimeout(function() {
        if (!player) {
          player = new YT.Player(videoOverlay.querySelector("iframe"), {
            videoId: videoId,
            width: "100%",
            height: "100%",
            playerVars: {
              autoplay: 0,
              controls: 0,
              rel: 0,
              showinfo: 0
            },
            events: {
              onReady: function() {
                player.mute();
              }
            }
          });
          players.push(player);
        } else {
          player.playVideo();
        }

        thumbnail.classList.add("hovered");
        videoOverlay.style.display = "block";
        thumbnail.querySelector(".title").style.opacity = 1;
      }, 2000);
    });

    thumbnail.addEventListener("mouseleave", function() {
      clearTimeout(hoverTimer);

      thumbnail.classList.remove("hovered");
      videoOverlay.style.display = "none";
      thumbnail.querySelector(".title").style.opacity = 0;

      if (player) {
        player.stopVideo();
      }
    });

    thumbnail.addEventListener("click", function(e) {
      e.stopPropagation();

      const lightbox = thumbnail.querySelector(".lightbox");
      const lightboxIframe = lightbox.querySelector("iframe");

      lightboxIframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1`;
      lightbox.classList.add("active");
    });
  });

  document.addEventListener("click", function() {
    const lightboxes = document.querySelectorAll(".lightbox");
    const lightboxIframes = document.querySelectorAll(".lightbox iframe");

    lightboxIframes.forEach(function(lightboxIframe) {
      lightboxIframe.src = "";
    });

    lightboxes.forEach(function(lightbox) {
      lightbox.classList.remove("active");
    });
  });
}

document.addEventListener("DOMContentLoaded", function() {
  const lightboxes = document.querySelectorAll(".lightbox");

  lightboxes.forEach(function(lightbox) {
    lightbox.addEventListener("click", function(e) {
      e.stopPropagation();
    });
  });
});

I want to play a YouTube video when I’m hovering for 2 seconds also when hovering over the thumbnails there should be a black opacity layer that covers the thumbnail and the title of the videos should fade in and when clicking on the thumbnail a lightbox should open ( Like when in full screen the lightbox should open ).

Why am I getting a ‘connection closed’ error when using NextJS 13.4’s streaming feature with React Suspense?

Error Image

THE ABOVE ERROR OCCURS when I tried to load more than two data with suspense (streaming). I’m using Next JS 13.4 with App router by the way.

export const serverApi = async <T>(
  url: string,
  init?: RequestInit
): Promise<T> => {
  const response = await fetch(BASE_URL.API + url, init);
  if (!response.ok) {
    throw new Error(response.statusText);
  }
  return await (response.json() as Promise<T>);
};
export const getArticles = async () => {
  return await serverApi<Article[]>(API.ARTICLES, {
    cache: "no-store",
  });
};

export const getArticle = async (id: string) => {
  return await serverApi<Article>(API.ARTICLE_WITH_ID(id), {
    cache: "no-store",
  });
};
const Header = async () => {
  return (
    <header className="relative w-full flex items-center justify-center">
      <div />
      <HeaderNavigation />
      <Suspense fallback={<HeaderProfileSpinner />}>
        {/* @ts-ignore */}
        <HeaderProfile />
      </Suspense>
    </header>
  );
};

const HeaderProfile = async () => {
  const cookie = getCookie();
  const queryClient = getQueryClient();

  await queryClient.prefetchQuery(USER_QUERY_KEYS.me(), () =>
    getUserMe(cookie)
  );

  const dehydratedState = dehydrate(queryClient);

  return (
    <Hydrate state={dehydratedState}>
      <HeaderProfileImage />
    </Hydrate>
  );
};

I use API like this. I’m using Page Router for API.
For more details, I use Prisma for ORM, Postgres (Supabase) for DB, and use Vercel deployment.
I think ‘connection closed’ means that the server aborts the connection when one of the streaming has resolved, and it wasn’t like I expected. I thought the whole point of streaming is rendering multiple contents in parallel but it didn’t work. It’s kinda weird that the error doesn’t happen in localhost.

how to implement a search bar with advance search option with dropdown values using react-JS

how to implement a search bar with advance search option with dropdown values using react-js.
how to design and implement it, when we click on group, a drawer will open and need to select those dropdown values and based on that we need to search globally.

I have tried with normal search ,I am expecting a drawer and submit functionality with dropdown values.image shows a group anchor based on that if we click a drawer will open and we need to select these dropdown values and submit.

Why doesn’t my React Native screen refresh when I make changes to the Login screen returned in App.js?

example:

export default function App() {
  return (
    LoginScreen()

When I try changing things the login screen, it doesn’t update in real time. However, when I use a Stack Navigator, then it updates. Why is that?

I expected that when I return the Login screen, it would update when I change the screen. To fix this, I used a stack navigator but don’t know why that fixed it.

Why does Javascript view while loops with and without curly braces differently? Can while loops without curly braces be nested?

I am working on a problem to determine whether a linked list is a Palindrome (Leetcode 234). I came across this (way above my level) solution.

var isPalindrome = function(head) {
    let slow = head, fast = head, prev, temp

    while (fast && fast.next)
        slow = slow.next, fast = fast.next.next
    prev = slow, slow = slow.next, prev.next = null

    while (slow)
        temp = slow.next, slow.next = prev, prev = slow, slow = temp
    fast = head, slow = prev

    while (slow) {
        if (fast.val !== slow.val) return false
        else fast = fast.next, slow = slow.next
    } //i added these curly braces because the solution still works with them
    return true
};

I was confused by the lack of curly braces so I added them to see if the loops were nested.

However, when I add curly braces to the second while loop, the code times out and if I add them to the first while loop, some test cases fail.

var isPalindrome = function(head) {
    let slow = head, fast = head, prev, temp
    while (fast && fast.next) {
        slow = slow.next, fast = fast.next.next
    prev = slow, slow = slow.next, prev.next = null
    }
    while (slow) {
        temp = slow.next, slow.next = prev, prev = slow, slow = temp
    fast = head, slow = prev;
    }
    while (slow) {
        if (fast.val !== slow.val) return false
        else fast = fast.next, slow = slow.next
      }
    return true
};

I also tried nesting the third while loop within the second like so,

var isPalindrome = function(head) {
    let slow = head, fast = head, prev, temp
    while (fast && fast.next) {
        slow = slow.next, fast = fast.next.next
    prev = slow, slow = slow.next, prev.next = null
    }
    while (slow) {
        temp = slow.next, slow.next = prev, prev = slow, slow = temp
    fast = head, slow = prev;
    while (slow) {
        if (fast.val !== slow.val) return false
        else fast = fast.next, slow = slow.next
      }
    }
    return true
};

and it still does not run. I have tried every variation of nesting possible with no luck, and I don’t even know what to Google so I can understand.

what am I missing here? I am so confused

any help would be extremely appreciated. Thank y’all

How to filter array object based on array object

I have the original data array. How to filter array object based on the array object

const products = [
  {
    options: [
       { id: 1, name: 'Size', value: '10'},
       { id: 2, name: 'Color', value: 'yellow'},
    ],
  },
  {
    options: [
       { id: 1, name: 'Size', value: '20'},
       { id: 2, name: 'Color', value: 'yellow'},
    ],
  },
  {
    options: [
      { id: 1, name: 'Size', value: '10'},
      { id: 2, name: 'Color', value: 'pink'},
    ],
  },
  { 
    options: [
      { id: 1, name: 'Size', value: '20'},
      { id: 2, name: 'Color', value: 'pink'}
    ],
  },
  {
    options: [
      { id: 1, name: 'Size', value: '39'},
      { id: 2, name: 'Color', value: 'pink'},
    ],
   },
];

And a filter array object:

const conditions = [
  [
    { name: 'Size',value: '10'},
    { name: 'Color', value: 'yellow'},
  ],
  [
    { name: 'Size', value: '10'},
    { name: 'Color', value: 'pink'},
  ],
];

My expected output is:

const outputProducts = [
  {
    options: [
      { id: 1, name: 'Size', value: '10'},
      { id: 2, name: 'Color', value: 'yellow'},
    ],
  },
  {
    options: [
      { id: 1, name: 'Size', value: '10'},
      { id: 2, name: 'Color', value: 'pink'},
    ],
  },
];

Here is my code. Try with a filter then find and some function. But I don’t know where is my mistake.

  const filterProducts = products.filter((el) => {
   return el.options.find((o) => {
     return conditions.find((m) => {
       return m.every(({ name, value }) => o.name == name && o.value === value);
     });
   });
 });

But did not get the correct result.
Thank you!!

How to fetch data with params from useSession in NextJS app?

Im using nextJs with the app router approach to fetch data. I am also using useSession from “next-auth” I need to fetch some data after getting the user id from the session object. I tried two appraoches. Approach 1: my fillSidebar() in useEffect doesnt have the session object yet and it would throw the error as expected. Approach 2. if i make my component function async, i get an infinite loop and i never get my session data and idk why

approach 1

import { useSession } from 'next-auth/react';
export const SideBar = () => {
  const { session } = useSession()
  const [categories, setCategories] = useState()
  useEffect(() => {
    const fillSidebar = async () => {
      try {
        const response = await fetch(`/api/category/${session?.user.id}`) //session is still null
        const data = await response.json()
        console.log(data)
        setCategories(data)
      } catch (error) {
        console.log(error)
      }
    }
    fillSidebar()
  }, [])

Approach 2:

import { useSession } from 'next-auth/react';

export const SideBar = async () => {
  const {data: session} = useSession()
  const fillSidebar = async()=>{
    try {
      await fetch(`/api/category/${session?.user.id}`)
      .then(response => response.json())
      .then(data =>  {return(data)})
    } catch (error) {
      console.log(error)
    }
  }
  const categories = await fillSidebar()

Approach 2 is what nextjs docs recommend for “sequential” data fetching, but they dont implement useSession

So if i want to keep using next-auth and its useSession hook, how can i fetch user related data?