Toggle icon symbol on click using js

In this menu, I’m trying to change the “+” symbol to “-” on click, but I don’t know how to proceed. It will be a button that I’ll change to custom icons later…

html

<header id="header">
      <div class="header-container">
        <p id="logo">Logo</p>
        <nav id="nav">
          <div id="btn-mobile">+</div>
          <ul id="menu">
            <li><a href="#">Sobre</a></li>
            <li><a href="#">Trabalhos</a></li>
            <li><a href="#">Carreiras</a></li>
            <li><a href="#">Contato</a></li>
          </ul>
        </nav>
      </div>
    </header>

js

const btnMobile = document.getElementById('btn-mobile');

function toggleMenu() {
  const nav = document.getElementById('nav');
  nav.classList.toggle('active');
}

btnMobile.addEventListener('click', toggleMenu);

thanks!

Why do have to use “use” before custom hook in react?

why do we have to use use before custom hook. Is this just a naming convention or there is something that React is doing internally to do something special?

CODESANDBOX LINK

I’ve created two custom hooks useCustomHook and customHook both are defined below. One with prefix use and other without. but while using useState hook in customHook eslint gives an error as:

enter image description here

why It is giving an error. Since the custom hook is just a normal function in which we can use other hooks in it. Below is the rule from React docs.

Unlike a React component, a custom Hook doesn’t need to have a
specific signature. We can decide what it takes as arguments, and
what, if anything, it should return. In other words, it’s just like a
normal function.
Its name should always start with use so that you can
tell at a glance that the rules of Hooks apply to it.

useCustomHook: with use Prefix

import { useState } from "react";

export default function useCustomHook(initialValue) {
  const [value, setValue] = useState(initialValue);

  function changeValue() {
    setValue((v) => v + 100);
  }

  return [value, changeValue];
}

customHook: without use Prefix

import { useState } from "react";

export default function useCustomHook(initialValue) {
  const [value, setValue] = useState(initialValue);

  function changeValue() {
    setValue((v) => v + 100);
  }

  return [value, changeValue];
}

Lararvel API with Nuxt

My goal is to pull in two separate data sets under the store directory. Eventually I want to have a categories list and an events list.

I started with a single set in the index.js file.

export const state = () => ({
    categories: []
  })
  
  export const getters = {
    categories (state) {
      return state.categories
    }
  }
  
  export const mutations = {
    SET_CATEGORIES (state, categories) {
      state.categories = categories
    }
  }
  
  export const actions = {
    async nuxtServerInit({ commit, dispatch }) {
      let response = await this.$axios.$get('categories')
  
      commit('SET_CATEGORIES', response.data)
    }
  }

This works exactly as I expect it to.

I copied it over to a category.js file, and changed index.js to

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import category from './category'

export default new Vuex.Store({
  modules: {
    category
  }
})
 

I expect to get the same list of the categories as before, but instead I get an error ‘Cannot read properties of undefined (reading ‘getters’)’. This solution was suggested on an old Laracasts Forum.

I went back to the Nuxt docs, but they seem to suggest it should look more like

import category from './category'

export const state = () => ({
    category: []
})

When I make these changes, I lose the error, but still don’t get any data back. But this doesn’t quite look right either anyway.

I have started going in circles with similar solutions, and nothing is quite clicking yet. Any ideas?

how to make expandable td

someone can tell me how i can make this td of “sintomas” expandable with js or css?
and I want when it is expanded it will overlap the others without affecting the heights and widths
here the image of what I want to do

  <tr class="hola">
            <td>2</td>
            <td>lautaro</td>
            <td>barrera</td>
            <td>[email protected]</td>
            <td>sa12312</td>
            <td>3541219667</td>
            <td> <img src="https://d29fhpw069ctt2.cloudfront.net/icon/image/39091/preview.png" alt="" style="height:9px;margin-right:10px">holaaaaaaaaaaaaaaaaaaaaadasdsadasdad </div></td>
            <td>Aceptado</td>
            <td>2022-06-27</td>
            <td>07:50:00</td>
            <td><a href="turno/2">Ver</a></td>
            <td><a href="editar/2">Editar</a></td>
            <td><a href="eliminar/2">Eliminar</a></td>

        </tr>
       

ANTD editable header row

I need to make an editable header row in a table. I’ve tried manipulating the first row as a header row, while the real header is hidden. It works well, but I got a problem when turning it into a new page because the first row won’t show up on the second page. Is there a possibility that I can customize and edit the table header row?

How to do cleanup in useEffect React?

Usually I do useEffect cleanups like this:

useEffect(() => {
    if (!openModal) {
      let controller = new AbortController();
      const getEvents = async () => {
        try {
          const response = await fetch(`/api/groups/`, {
            signal: controller.signal,
          });
          const jsonData = await response.json();
          setGroupEvents(jsonData);
          controller = null;
        } catch (err) {
          console.error(err.message);
        }
      };
      getEvents();
      return () => controller?.abort();
    }
  }, [openModal]);

But I don’t know how to do in this situation:

I have useEffect in Events.js file that get events from function and function in helpers.js file that create events on given dates except holidays (holiday dates fetch from database).

Events.js

useEffect(() => {
    if (groupEvents.length > 0) {
      const getGroupEvents = async () => {
        const passed = await passEvents(groupEvents); // function in helpers.js (return array of events)
        if (passed) { 
          setEvents(passed.concat(userEvents));
        } else {
          setEvents(userEvents);
        }
      };
      getGroupEvents();
    }
  }, [groupEvents, userEvents]);

helpers.js

const passEvents = async (e) => {
  try {
    const response = await fetch(`/api/misc/holidays`, {
      credentials: 'same-origin',
    });
    const jsonData = await response.json();
    const holidays = jsonData.map((x) => x.date.split('T')[0]); // holiday dates
    return getEvents(e, holidays); // create events
  } catch (err) {
    console.error(err.message);
  }
};

next.js wont let me return in a promise

For background on the problem, my code was working fine in run dev with if-else statements however in run build the if-else didn’t work so now I’m trying new ways of conditionally rendering a page. This one is the most promising however the return statement inside doesn’t work. Is there a fix? If I replace it with a console.log it returns the text to the console, so it has something to do with the promise.

import { useAddress } from "@thirdweb-dev/react";
import Head from 'next/head';
import Link from 'next/link';
import Username from '../components/Username';
import React from "react";



const Home = () => {

    let p = new Promise((resolve, reject) => {
        let address = useAddress();
        if (address) {
            resolve(address)
        } else {
            console.log('no addy')
            reject()
        }
    })
    
    p.then((address) => {
        return (
            <>
                <Head>
                    <title>DRUMM3R</title>
                    <link rel="icon" href="/drum.svg" />
                </Head>
                <Username address={address} />
            </>
        );
    }).catch(() => {
        return (
            <>
                <Head>
                    <title>DRUMM3R</title>
                    <link rel="icon" href="/drum.svg" />                
                </Head>
                <Link href="/">
                    <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">click here to log in</a>
                </Link>
            </>
        );
    })        
}

export default Home;

discord.js – Invalid Form Body

I tried to find the answer, but none of the things I looked at had basically any code relating to mine. I tried running the command in my server, but then it gave the error, “DiscordAPIError: Invalid Form Body”

if (message.content === "*whois") {
const whoisembed = new Discord.MessageEmbed()
    .setTitle(message.author.username+"'s info")
    .setImage(message.author.avatar)
    .setDescription("ID: "+message.author.id);
    message.channel.send({embeds:[whoisembed]});
    }

Loop with setInterval

Sup, hope you all doing well!

I’m tryng to change each piece of a string to a random digit in a realtime loop but something is going bad here

I’ve shorted the code to find the problem but no sucess atm:

let count = 0;
let timer = setInterval(() => {
let rng = Math.floor(Math.random()*9);
let txtOriginal = document.getElementsByTagName('p')[0].innerHTML;

if (count < 8) {

let txtNew = document.getElementsByTagName('p')[0].innerHTML = txtOriginal.replace(txtOriginal.charAt(count), rng);
count++;

} else {
count = 0;
}
},500) 
<p>ABCDEFGH</p>

The first run goes as intended, but going foward it starts to change the values in a random order…

Should I try another metod?

Can I have the className of a leaflet divIcon inside the section of a vue component?

I have a Vue 2 sample project at https://github.com/ericg-vue-questions/leaflet-test

When declaring the divIcon, I have:

      const cloudIcon = L.divIcon({
        html: thecloud,
        className: 'my-custom-icons',
        iconSize: [size, size],
        iconAnchor: [size/2, size/2]
      })

and, for leaflet to see the my-custom-icons style, I wrote:

<style scoped>
  #mapContainer {
    width: 500px;
    height: 500px;
  }
</style>

<style>
  .my-custom-icons {
    background-color: red;
  }
</style>

I would like the style section to look like:

<style scoped>
  #mapContainer {
    width: 500px;
    height: 500px;
  }

  .my-custom-icons {
    background-color: red;
  }
</style>

But when I place my-custom-icons inside of the components scoped section, the divIcon cannot find it.

Can I organize my style section like this? If so, how?

Why is my fetched api data not displaying?

I fetched some data from a third party API and then console.logged it. However, it is displaying as null in the console (It is actually an empty string). Something I noticed was that it was requested multiple times. How can I store the string into a variable? Is it a problem with the way I get the data or is it how I am storing it?

import { ThemeProvider, createTheme } from "@mui/material/styles";
import React from "react";
import { CssBaseline } from "@mui/material";
import { useState } from "react";
import { Alert } from "@mui/material";
import { useEffect } from "react";
// Dark theme

function App() {
  const [ready, setReady] = useState(false);
  const [requestUrl, setRequestUrl] = useState("");
  const [zuhrtime, setZuhrtime] = useState("");
  useEffect(() => {
    fetchData();
  }, [ready]);

  const darkTheme = createTheme({
    palette: {
      mode: "dark",
    },
  });

  // api variables
  const api1 = "https://api.aladhan.com/v1/timings/";
  const api2 = "?latitude=";
  const api3 = "&longitude=";
  // Get location
  const [showAlert, setShowAlert] = useState(false);
  const getMyLocation = () => {
    const success = (position) => {
      //console.log(position);
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;
      const timestamp = position.timestamp;
      setRequestUrl(api1 + timestamp + api2 + latitude + api3 + longitude);
      setReady(true);
      //console.log(requestUrl);
      //console.log(timestamp);
      setShowAlert(true);
      setReady(true);
    };
    const error = () => {
      console.log("error");
      setShowAlert(false);
    };
    navigator.geolocation.getCurrentPosition(success, error);
  };

  // Get request from api
  const fetchData = async () => {
    const response = await fetch(requestUrl);
    let adata = await response.json();
    console.log(adata);
    setZuhrtime(adata.status); // what I want to display
    setZuhrtime(adata.data.timings.Dhuhr); // also what I want to display
    console.log(zuhrtime);
  };

  return (
    <ThemeProvider theme={darkTheme}>
      <CssBaseline />
      <h2>
        {showAlert ? (
          <Alert variant="filled" severity="success">
            Location Accessed
          </Alert>
        ) : (
          <Alert variant="filled" severity="error">
            Unable to get location. Enable location to use this
          </Alert>
        )}
      </h2>

      {getMyLocation()}
    </ThemeProvider>
  );
}

export default App;