Why is Google Analytics and Optimize not reporting my experiment traffic?

Not sure why this isn’t working. But i have a Google Optimize experiment setup…

It changes the string in a title

The variant page loads correctly

The Optimize experiment itself connected properly to my app

I added the gtag.js script to my app through Google Tag Manager

<script type="text/javascript" id="" src="https://www.googletagmanager.com/gtag/js?id=UA-12345678-1"></script>

And

window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date);gtag("config","UA-12345678-1");

It is a custom html tag in GTM which i got warned not to do, but not sure how else to put it in.

The page is tracking as a page viewed in the main GA real time info. But when i click “View my report in Analytics” in Optimize, it takes me into GA, where there’s no hits being recorded. It’s just 0% bounces / activity.

What have i done wrong?

Clicking anywhere on the page besides the 3 menu items hide any visible menu

  The corresponding dropdown element should display below it
  BONUS: Clicking anywhere on the page besides the 3 menu items
  hide any visible menu item
  Look into the matches() function
  Hamburger icon / nav elements:
  When user clicks hamburger icon, side menu should be displayed
  When user clicks “close” button in side menu, it should be hidden again
  You should only be adding JS here!
  My HTML and CSS are identical in the starter & solution code

  HTML
   <ul class="nav">
   <li id="menu-1-button">Why Slack?</li>
   <li id="menu-2-button">Solutions</li>
   <li id="menu-3-button">Resources</li>
   <li>Pricing</li>
   </ul>
   </section>
   <div class="nav-right">
   <p class="workspaces">Your Workspaces</p>
   <div class="hamburger-menu" id="menu-trigger">
   <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/hamburger.svg"         alt="Hamburger icon">
   </div>
   </div>
   </header>

   <!--Main content-->
   <section class="placeholder"></section>

   <!--Side menu-->
   <aside class="side-menu-position side-menu-design" id="side-menu">
   <header class="side-menu-header">
   <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/slack.svg"         alt="Slack logo">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/x.svg" alt="Close     this menu" id="menu-close">
    </header>
    <ul class="side-menu-content">
     <li>Why Slack?</li>
     <li>Pricing</li>
     <li>About Us</li>
     <li class="side-menu-workspace">Your Workspaces</li>
     <li class="side-menu-download">Download Slack</li>
     </ul>
     </aside>

    <!--Dropdown Menus, notice how they are asides listed just inside the body - no deeper -->
     <aside class="dropdown-menu" id="menu-1">
     <h2 class="menu-header">About the Product</h2>
     <ul class="menu-item-list">
     <li><a href="#">How it works</a></li>
     <li><a href="#">Security</a></li>
      <li><a href="#">Customers</a></li>
    <li><a href="#">Enterprise</a></li>
    </ul>
    </aside>

    <aside class="dropdown-menu" id="menu-2">
   <h2 class="menu-header">Slack for Every Team</h2>
   <ul class="menu-item-list">
   <li><a href="#">Engineering</a></li>
   <li><a href="#">IT</a></li>
    <li><a href="#">Customer Support</a></li>
   <li><a href="#">Project Management</a></li>
   <li><a href="#">Sales</a></li>
   <li><a href="#">Marketing</a></li>
   <li><a href="#">Human Resources</a></li>
   </ul>
   </aside>

   <aside class="dropdown-menu" id="menu-3">
   <h2 class="menu-header">Go Further With Slack</h2>
   <ul class="menu-item-list">
   <li><a href="#">Download</a></li>
   <li><a href="#">Blog</a></li>
  <li><a href="#">Help Center</a></li>
  <li><a href="#">e-Books</a></li>
  <li><a href="#">Reports</a></li>
  <li><a href="#">API</a></li>
  </ul>
 </aside>

 CSS

 body {
 font-family: 'Lato', sans-serif;
 color: #454545;
}

.placeholder {
 background: lightslategray;
 height: 100vh;
}

.global-header {
 background-color: white;
 display: flex;
 flex-direction: row;
 justify-content: space-between;
 height: 40px;
 padding: 15px 25px;
 width: calc(100% - 50px);
 }

/* NAV */

.nav-left {
 align-items: center;
 display: flex;
}

.logo {
display: flex;
 align-items: center;
 }

 .logo svg {
  width: 150px;
 }

 .nav {
  display: none;
 flex-direction: row;
 align-items: center;
 margin: 0;
 padding-left: 0;
}

 @media (min-width: 1085px) {
 .nav {
 display: flex;
 }
}

   ul {
   list-style: none;
   }

    .nav li {
      font-size: 14px;
     margin: 0 20px;
     cursor: pointer;
    }

     .nav-right {
      align-items: center;
      display: flex;
      justify-content: flex-end;
      margin-right: 45px;
     }

   /* DROPDOWN MENU */

   .dropdown-menu {
    background-color: white;
    box-shadow: 0 0 2rem rgba(0,0,0,.1); 
    /* `display: none` hides the element when the page loads - how could we change    this    when our JS event takes place? */
     display: none;
     padding: 15px;
     position: absolute; /* pops element up in the dom */
     top: 60px;
     width: 250px;
     z-index: 10;
   }

     /* element has this class and ID */
        .dropdown-menu#menu-1 {
        left: 190px;
     }

     .dropdown-menu#menu-2 {
     left: 290px;
     min-width: 400px;
    }

    .dropdown-menu#menu-3 {
     left: 390px;
     min-width: 400px;
    }

  .menu-header {
   font-size: 12px;
    margin: 0;
    padding: 0 10px 8px 10px;
    text-transform: uppercase;
   }

  .menu-item-list {
   margin: 0;
   padding-left: 0;
  }

  /* https://developer.mozilla.org/en-US/docs/Web/CSS/columns 
  
Guide to Responsive-Friendly CSS Columns
*/ #menu-2 .menu-item-list, #menu-3 .menu-item-list { column-count: 2; column-gap: 20px; } .menu-item-list li a, .menu-item-list li a:visited, .menu-item-list li a:focus { color: #454545; display: block; padding: 10px; text-decoration: none; } .menu-item-list li a:hover { background-color: rgb(242,242,242); color: #1264a3; } /* Fade-in header */ #fade-in-header { display: none; position: fixed; top: 0; } #top-nav { position: fixed; } .show { display: block; } /* SIDE MENU */ .workspaces { background-color: #611f69; border-radius: 10px; color: white; cursor: pointer; display: none; padding: 8px 16px; transition: all 420ms ease-in-out; } /* Notice you can do a hover state on an element, not just <a> links */ .workspaces:hover { background-color: #4a154b } @media (min-width: 1085px) { .workspaces { /* Hidden below 1085px - see above rule */ display: block; } } .hamburger-menu { display: block; /* display:none starts to show up with responsive */ cursor: pointer; } @media (min-width: 1085px) { .hamburger-menu { display: none; } } /* OFF CANVAS MENU * Slack has an image with a translucent bg which combines bg color and image together * position: fixed with 0,0,0,0 positions streches across the viewport * z-index: 2 keeps it on top of the rest of the page * I'm breaking the side-menu parent into two styles, one position and on design, so you can see how this looks better * You don't have to do it this way at all...but it helps to see the separation of concerns here */ .side-menu-position { padding-top: 25px; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 2; } .side-menu-design { background-color: #611f69; background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/2522641/sidebar-background.png'); background-size: 1300px 700px; background-repeat: repeat; cursor: pointer; opacity: 0; transform: translateX(100%); transition: 0.4s ease-in-out; } /* on top we need spacing from the border, so we have to use padding */ /* but we also want that bottom margin to bleed to the edge, so no margins here */ .side-menu-header { border-bottom: 1px solid rgba(255,255,255,.1); /* based on slack look, very faint */ display: flex; justify-content: space-between; padding: 0 25px 25px 25px; } /* Main content is pretty easy for layouts, pattern you'll see in web dev */ /* The more text an element has, the easier it is to layout - BAM wisdom bomb! */ .side-menu-content { color: #fff; font-size: 24px; /* could use ems here too */ margin: 25px; padding-left: 0; } .side-menu-content li { list-style: none; margin-bottom: 25px; } .side-menu-workspace { margin-bottom: 8px; text-align: center; } .side-menu-download { background-color: #fff; color: #611f69; padding: 15px 0; text-align: center; width: 100%; } /* Sticks the nav to the top of the page */ #top-nav { position: fixed; } /* Animation classes */ .show-menu { opacity: 1; transform: translateX(0%); } JavaScript const menu1Button = document.getElementById('menu-1-button'); const menu2Button = document.getElementById('menu-2-button'); const menu3Button = document.getElementById('menu-3-button'); // We'll also assign all 3 of our menu dropdown elements to variables const menu1Dropdown = document.getElementById('menu-1'); const menu2Dropdown = document.getElementById('menu-2'); const menu3Dropdown = document.getElementById('menu-3'); // Note that we are never reassigning the value of any of these variables - which is why we're using the `const` keyword instead of the `let` keyword // Okay. Let's talk through what functionality we want for one button. Let's start with the first menu element - "Why Slack?" - we've stored that as `menu1Button` variable above. // So we'll have something like: // menu1Button.addEventListener("someevent", someFunction);

// What’s the event? It’s when the user clicks that element. What event is that in JS? It’s the “click” event – https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

 // So now we have:
 // menu1Button.addEventListener("click", someFunction);

 // Now we need the function to run! Let's not name it `someFunction` - we'll name it after the functionality we want it to execute! We want it to display the first dropdown menu element - so how about `displayMenuOne`?

 // So now we have:
 // menu1Button.addEventListener("mouseover", displayMenuOne);

  // Now we just need our `displayMenuOne` function!
  // It should *display* the element with ID "menu-1" - stored as `menu1Dropdown` variable above.
  // How can we edit that element to display it? We *could* use the "style" property (remember when we did `document.body.style.backgroundColor` in the color switcher activity in Lesson 10?).
  // However, it's easier to use CSS classes - and we have this `.show` rule in our CSS... so let's just add the "show" class to the "menu1Dropdown" element  

 // function displayMenuOne() {
 //   menu1Dropdown.classList.add("show");
// }

 // Last piece: what if one of the other dropdowns is being displayed? Remember - we don't always want to rely on the initial state of our page. The initial state is that none of the dropdowns are displayed, but what if I've clicked on `menu1Button` when the second menu is already visible?

 // Let's make sure to remove the `show` class on our other 2 dropdown elements, whether or not that class is present on the element.

// So we end up with:

 menu1Button.addEventListener("click", displayMenuOne);

 function displayMenuOne() {
 menu1Dropdown.classList.add("show");
 menu2Dropdown.classList.remove("show");
 menu3Dropdown.classList.remove("show");
}

// Let's repeat this for our other 2 menu button elements.
 menu2Button.addEventListener("click", displayMenuTwo);
 menu3Button.addEventListener("click", displayMenuThree);

 function displayMenuTwo() {
 // show menu 2
 menu2Dropdown.classList.add("show");
 // hide menus 2 and 3 if they are open
  menu1Dropdown.classList.remove("show");
  menu3Dropdown.classList.remove("show");
  }

  function displayMenuThree() {
  // show menu 3
  menu3Dropdown.classList.add("show");
  // hide menus 1 and 2 if they are open
  menu1Dropdown.classList.remove("show");
  menu2Dropdown.classList.remove("show");
  }

 // SIDE MENU

 // There's a menu icon present at or below a viewport width of 1085px.
// It has the ID of `menu-trigger`.
// Let's assign it to a variable.

 const menuDisplayButton = document.getElementById('menu-trigger');

// What event are we listening for on that element?
// A click!

 menuDisplayButton.addEventListener("click", displaySideMenu);

// When the side menu is visible, it has a close button with ID `menu-close`.
// Let's add a click listener for that element that will hide the side menu.

 const menuCloseButton = document.getElementById("menu-close");
 console.log(menuCloseButton);
 menuCloseButton.addEventListener("click", hideSideMenu);

 // Now we just need these 2 functions - `displaySideMenu` and `hideSideMenu`
// The class that displays our side menu element is `show-menu`
// so `displaySideMenu` will add that class to the side menu element
// and `hideSideMenu` will remove that class

const sideMenu = document.getElementById('side-menu');

function displaySideMenu() {
sideMenu.classList.add("show-menu");
}

function hideSideMenu() {
sideMenu.classList.remove("show-menu");
}

The corresponding dropdown element should display below it
BONUS: Clicking anywhere on the page besides the 3 menu items
hide any visible menu item
Look into the matches() function
Hamburger icon / nav elements:
When user clicks hamburger icon, side menu should be displayed
When user clicks “close” button in side menu, it should be hidden again
You should only be adding JS here!
My HTML and CSS are identical in the starter & solution code

Please focus on the bonus part

How to Re-render a Map created with React Leaflet when Incoming Props Change

I am stuck trying to trigger a re-render of the upon changes in props.

The App.js file initializes state and sets the latitude and longitude to empty strings and the state is updated with the results of an API call. The new values of state are then passed to the for its use in determining the position of the marker on the map.

The challenge I am having now is how to ensure that the newProps received in the component leads to a re-render of the component.

The code in APP.js is as follows

import React from "react"
import './App.css';
import AddressHeader from "./Components/AddressHeader"
import AddressDetails from "./Components/AddressDetails"
import AddressMap from "./Components/AddressMap"

export default function App () {

  //State will be created here in the APP.js file and passed to child components via props
  const [visitorDetails, setVisitorDetails] = React.useState({
    ipAddress : "",
    city: "",
    timezone: "",
    ISP: "",
    latitude: "",
    longitude: ""
 });

 React.useEffect(() => { //Fetch data from the API only once, hence the dependencies array has the element 0
    fetch("https://geo.ipify.org/api/v2/country,city?apiKey=at_weFpeQS6scjef5CE5Bf9il4OXCNfM")
    .then(res => res.json())
    .then(data => setVisitorDetails({      
          ipAddress: data.ip,
          city: data.location.city,
          timezone: data.location.timezone,
          ISP: data.isp,
          latitude: data.location.lat,
          longitude: data.location.lng
       
    }));
 }, [0])

  return (
    <section>
      <AddressHeader />
      <AddressDetails 
        ipAddress = {visitorDetails.ipAddress}
        city = {visitorDetails.city}
        timezone = {visitorDetails.timezone}
        ISP = {visitorDetails.ISP}
        />
      <AddressMap 
        latitude = {visitorDetails.latitude}
        longitude = {visitorDetails.longitude}
      />
    </section>
  )
}

And the code in component is as follows

import React from "react"
import map from "../ComponentStyle/Map.module.css"
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'



export default class AddressMap extends React.Component {

    constructor () {
        super()
        this.state = {
            latitude: "",
            longitude: ""
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
      if(nextProps.latitude !== this.props.latitude) {
        return true
      } 
    }

    render () {
        return (
            <MapContainer center={[this.state.latitude, this.state.longitude]} zoom={13} scrollWheelZoom={false} className = {map.mapContainer}>
            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position = {[this.state.latitude, this.state.longitude]} >
               <Popup>
                  A test marker and popup
               </Popup>
            </Marker>
          </MapContainer>
        )
    }
}

how to open a html file by onclick?

I am trying to open a html file when I click on an image. I like to open the html file in my current browser. Is that possible?



const clock = document.createElement('div')

clock.innerHTML = '<img src="https://png.pngtree.com/png-vector/20190912/ourlarge/pngtree-clock-icon-in-flat-style-png-image_1728101.jpg" height = "60px" width="60px"alt="NI">';

clock.onClick = function () {
    window.open('file:///Users/puyang/Desktop/clock/popup.html')
}
document.body.append(clock)


how to filter child elements in jquery

trying to create a search filter based on an list in a razor view:

<input class="form-control" id="foodSearch" type="text" placeholder="Search here...">
<br>
<ul class="list-group" id="foods">
    @foreach (var f in @Model)
    {
        <li>
            <div id="food">
                <p">@f.Name</p>
                <small>@f.prepTime, @f.price </small>
            </div>
        </li>

    }
</ul>


$("#foodSearch").on("keyup", function () {
        var value = $(this).val().toLowerCase();
    $("#foods li div").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });

so essentially I am trying to filter based on the values contained within the ‘p’ and ‘small’ tags, and then only that ‘parent’ div be left in the search

Getting a stored jwt cookie and verifying it

I’m trying to make it so that some pages only render whenever an user is logged in. However, I can’t seem to find any documentation on how to retrieve cookies using vue.js. My project is being made with the mevn stack. And I saved the user cookie with:

        res.cookie('token', token, {
            maxAge: 24 * 60 * 60 * 1000,
            httpOnly: true
        });

The problem I’m facing now is retrieving this cookie, so that I can verify wether the user is logged in. I can’t find anything on how to do this, so I’m asking it here.

/pages/crash.vue

data() {
        return {
            foo: false,
        };
    },
    mounted() {
        // Get cookie
        // If cookie is valid 
        // Set this.foo to true
        if (this.foo) {
            ...
        } else {
            window.location.href = '/login'
        }
    },

Write multiple values from json file into HTML table with Javascipt

Heyy!

I have a small problem and I am still a beginner. That’s why I haven’t found a solution yet. ^^

There is a json file with multiple values. I would like to write the values from the file into an HTML table with Javascript (not php!).


Here is an example:

Json File:

{
   "628e191673ae8f7750c62fce": {
     "name": "John",
     "surname": "Smith",
     "age": "24"
   },
   "628e1fd0d27981c6250d886c": {
     "name": "Fred",
     "surname": "Bloggs",
     "age": "32"
   },
   "628e20c805f38641bdc08d7d": {
     "name": "Joe",
     "surname": "Harris",
     "age": "27"
   }
}

The table should then look like this:

Name Surname Age
John Smith 24
Fred Bloggs 32
Joe Harris 27

What is the best way for me to do this with Javascript?
Thank you in advance. 🙂

How to mock NODE_ENV in unit test using Jest

I want to set NODE_ENV in one of the unit test but it’s always set to test so my tests fails.

loggingService.ts

...

const getTransport = () => {
  if (process.env.NODE_ENV !== "production") {
    let console = new transports.Console({
      format: format.combine(format.timestamp(), format.simple()),
    });
    return console;
  }

  const file = new transports.File({
    filename: "logFile.log",
    format: format.combine(format.timestamp(), format.json()),
  });
  return file;
};

logger.add(getTransport());
const log = (level: string, message: string) => {
  logger.log(level, message);
};

export default log;

loggingService.spec.ts

     ...
    describe("production", () => {
        beforeEach(() => {
          process.env = {
            ...originalEnv,
            NODE_ENV: "production",
          };
    
          console.log("test", process.env.NODE_ENV);
          log(loglevel.INFO, "This is a test");
        });
    
        afterEach(() => {
          process.env = originalEnv;
        });
    
        it("should call log method", () => {
          expect(winston.createLogger().log).toHaveBeenCalled();
        });
    
        it("should not log to the console in production", () => {
          expect(winston.transports.Console).not.toBeCalled();
        });
    
        it("should add file transport in production", () => {
          expect(winston.transports.File).toBeCalledTimes(1);
        });
      });
...

How can I set process.env.NODE_ENV to production in my tests preferably in the beforeEach such that the if block in my service is false and the file transport is returned. I have omitted some code for the sake of brevity.

What is more performant way to request an image using Axios and proccess it (Blob vs Buffer)?

I am looking for a workaround to authenticate image requests in a RESTful app, see JWT-based authentication for tags?. I’ve come to a solution which uses Axios to grab the images via api routes (where the auth layer is already set).

I’ve tested two ways to grab a binary resource via axios, one is using a blob the second an arraybuffer, they both seemed to work fine:

Blob / FileReader, ReadAsDataUrl:

const SecuredImageAsBlob = ({ path, ...props }: Props) => {
  const [imageDataUrl, setImageDataUrl] = useState<string | ArrayBuffer | null>()
  useEffect(() => {
    axiosWithAuthHeaders
      .get(`/securedimage/${path}`, {
        responseType: "blob",
      })
      .then(response => {
        var reader = new window.FileReader()
        reader.readAsDataURL(response.data)
        reader.onload = function () {
          setImageDataUrl(reader.result)
        }
      })

    return () => {}
  }, [path])
  return imageDataUrl ? <img src={String(imageDataUrl)} {...props} /> : null
}

vs Buffer / toString("base64"):

const SecuredImageAsBuffer = ({ path, ...props }: Props) => {
  const [base64string, setBase64string] = useState<string | null>()
  useEffect(() => {
    axiosWithAuthHeaders
      .get(`/securedimage/${path}`, {
        responseType: "arraybuffer",
      })
      .then(response => {
        const buffer = Buffer.from(response.data, "binary").toString("base64")

        setBase64string(buffer)
      })

    return () => {}
  }, [path])
  return base64string ? <img src={`data:image/png;base64,${base64string}`} {...props} /> : null
}

But which one is more performant? I would say the Blob with FileReader() and readAsDataUrl, because it is reading a stream, so it can start to paint the image before it is fully loaded (which is close to the native <img /> behaviour). Buffer, on the other hand, has to be fully loaded and then converted to base64 before it can be shown as image, and I also guess it would take more memory because the size would be bigger. But I might be completely wrong, so feel free to correct me!

What do you thing? Blob / FileReader, Buffer / base64, or some other way I completely missed?

How download and after delete file JQUERY

Can I download file if I get full way to him? And then delete it?

That’s my folders

folders

My jquery in static/js/my_jquery. I need to get file from data/Expenses01.xlsx after ajax.done

$.ajax({
    type: "POST",
    url: "/create_excel/" + url,
    data: JSON.stringify(for_download),
    contentType: "application/json; charset=utf-8",
    async: false
}).done((response) => {
    console.log(response)
});

In response I get full way to file

My response

Flask code which return way, but I think that’s don’t very important

@bp.route('/create_excel/', methods=['POST', 'GET'])
def export_excel():
    filename = excel()
    print(request.json['Test'])
    return redirect(url_for('main.download_file', filename=filename))


@bp.route('/download_file/')
def download_file():
    filename = request.args['filename']
    return filename
    # return send_file(filename, mimetype='text/xlsx', as_attachment=True)

I click button then call ajax which call python function which create file, after I need to download this, return send_file/send_from_dictionary doesn’t work and I want to try download in ajax.done

There’s my project on git:
https://github.com/Danila0987654/Flask_download_files

Uncaught (in promise) FirebaseError: Expected type ‘wc’, but it was: a custom Vc object

The indicated error appears on line //line29, and I am not able to find the error within the code, can someone help me?
the code is to show the information of the registered users when it is searched through the cpf;

   const app = initializeApp(firebaseConfig);
   const db = getFirestore(app);

async function GetADocument(){
var Ref =  setDoc(db, 'cpf', pesquisa.value);
const docSnap  = await getDocs(Ref);

  if(docSnap.exists(cpf = pesquisa)){
    nome.value = docSnap.data().nome;
    endereco.value = docSnap.data().endereco;
    bairro.value = docSnap.data().bairro;
    cidade.value = docSnap.data().cidade;
    uf.value = docSnap.data().uf;
    cep.value = docSnap.data().cep;
    rg.value = docSnap.data().rg;
    cpf.value = docSnap.data().cpf;
    nascimento.value = docSnap.data().nascimento;
    tel.value = docSnap.data().tel;
    cel.value = docSnap.data().cel;
    titulo.value = docSnap.data().titulo;
    zona.value = docSnap.data().zona;
    secao.value = docSnap.data().secao;
    pai.value = docSnap.data().pai;
    mae.value = docSnap.data().mae;
  }
   else{
    alert("usuário não encontrado");
   }
} //line29

btnbuscar.addEventListener("click", GetADocument);


Dropdown / close block

On this in my application there is a filter button, when clicked, the user can see a list (done using a modal window) of categories for filtering (Categories are: Method, Status code, Link, Date). Visually, the filter window looks like this:

enter image description here

However, I would like all categories (Method, Status code, Link, Date) to be collapsed and expanded. Schematically, this can be shown as follows:

enter image description here enter image description here

My code is divided into blocks (for each filter category there is a separate file).
Here I will give an example of how I built the filtering by Method.
And I will be grateful if you tell me how to change it in such a way that this category could open and close (for the rest of the categories I will do it myself)

export default function FilterMethod  () {
const [methods, setMethods] = useState([]);

const onMethodChange = (e) => {
    let selectedMethods = [...methods];

    if (e.checked)
        selectedMethods.push(e.value);
    else
        selectedMethods.splice(selectedMethods.indexOf(e.value), 1);

    setMethods(selectedMethods);
}

return (
        <div>
            <h6>Method</h6>
            <div style={{display: "flex"}}>
                <Checkbox inputId="method1" name="method" value="Connect" onChange={onMethodChange} checked={methods.indexOf('Connect') !== -1} />
                <label  htmlFor="method1">Connect</label>
            </div>

            <div style={{display: "flex"}}>
                <Checkbox inputId="method2" name="method" value="Delete" onChange={onMethodChange} checked={methods.indexOf('Delete') !== -1} />
                <label htmlFor="method2">Delete</label>
            </div>

         // Here I shortened the code, since it's just a list of methods

        </div>

)}

.css file

    input[type="checkbox"] {
    width: 50px;
    height: 18px;
    vertical-align: middle;
}

Cant pass state to a conditional?

Working on an app where you can post your video game clips. Have two fetches for clip data that are the same thing just ordered in two different ways in the backend (default, and most comments). Trying to render the fetches conditionally. Seems to work when I change line 4 to switchFetches === true. But not when I press the button that changes switchFetches to false.

App

const [switchFetches, setSwitchFetches] = useState(true);

  useEffect(() => {
    if (switchFetches === false) {
      fetch("/most_comments")
        .then((r) => r.json())
        .then((data) => setClipData(data));
    } else {
        fetch("/clips")
        .then((r) => r.json())
        .then((data) => setClipData(data));  
    }
  }, []);

ClipList

function onChangeForFilter(e) {
    e.preventDefault();
    setSwitchFetches(false)
  }