When should I use a custom equality function in useSelector()?

I’m trying to understand when it is necessary to use a custom equality function in useSelector().

I have a selector that returns a simple object as:

const data = useSelector(state => state.data) // => { a: "foo", b: "bar }

I though that since data is an object, I needed to use a custom equality function to avoid unnecessary re-render, as it is stated in the doc:

With useSelector(), returning a new object every time will always force a re-render by default.

But then I noticed that my component was only re-rendering when data changed. I assumed that maybe the default equality function works with objects, but to be sure I tried to use a custom function:

const data = useSelector(state => state.data, (a, b) => a === b));

If data didn’t change, it will always return true.

In Javascript, if I try to compare two objects with === it will return false because the references are different. But here with useSelector(), since it returns true it means that the references are the same.

Now, I’m not sure if I misunderstood the doc, but I wonder when I should use a custom equality function such as the isEqual of Lodash?

I’m using Redux Toolkit, if it makes any difference. Here is a CodeSandox if you want to test.

Is there a way to improve performance in a React 18 application when navigating away from a page with many components?

I recently updated from React 16 to React 18 and performance during rendering has decreased substantially. The issue appears to be that unmounting components is a slow process. I ran a performance analysis navigating away from the same page and I can see that when I am using React 18 the event handler on page transition takes almost 3 seconds versus 750ms for the same thing in React 16. I am also seeing this lagging behavior any time a component with many children (like a table) is removed from the DOM. Running the React Profiler shows “react commit” is taking up most of the time. Is there some way to make improve React 18 performance when removing components from the screen? Has anyone else noticed this behavior?

I included screenshots of the performance analysis from clicking on a link to navigate away from a page with a table.

React 18 performance

React 16 Performance

Discord.js: Cannot read properties of undefined (reading ‘remove’)

I am trying to make a support system but an error occurred in my presenceUpdate event. Could you help me please?
Thanks in advance

PS: I am French and I use a translator, I excuse myself for the imprecisions.

Event presenceUpdate.js :

module.exports = (client, oldMember, newMember, newPresence) => {
    client.guilds.cache.forEach(guild => {
      let { soutien_role_id: soutienRoleId, soutien_text: soutienText } = client.db.settings.selectSoutien.get(guild.id);

      if(soutienRoleId && soutienText) {
        
        if (!oldMember) return;
        if (oldMember === undefined || newMember === undefined) return;
        if (oldMember.status !== newMember.status || oldMember == undefined || newMember == undefined) return;
        if (guild.members.cache.get(newMember.user.id) === undefined) return;
        
        const soutienRole = guild.roles.cache.get(`${soutienRoleId}`);
        const word = soutienText
        const members = newMember.guild.members.cache;
        let status = members.filter(m => m.presence?.status !== "offline")
        status = Array.from(status)
          
        if(!members) return;
        
        if(status[0] && status[0].includes(word)) {
            members.roles.add(soutienRole)
          } else {
            if(guild.roles.cache.some(r => r.id === soutienRoleId)) {
              guild.members.roles.remove(soutienRole)
            }
          }
        }
      })
    }

Error :

{
  "stack": "TypeError: Cannot read properties of undefined (reading 'remove')
    at C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z\src\events\presenceUpdate.js:24:35
    at _Collection.forEach (<anonymous>)
    at module.exports (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z\src\events\presenceUpdate.js:2:25)
    at Client.emit (node:events:537:28)
    at PresenceUpdateAction.handle (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z        
ode_modules\discord.js\src\client\actions\PresenceUpdate.js:37:19)
    at module.exports [as PRESENCE_UPDATE] (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z
ode_modules\discord.js\src\client\websocket\handlers\PRESENCE_UPDATE.js:4:33)
    at WebSocketManager.handlePacket (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z      
ode_modules\discord.js\src\client\websocket\WebSocketManager.js:346:31)
    at WebSocketShard.onPacket (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z
ode_modules\discord.js\src\client\websocket\WebSocketShard.js:478:22)
    at WebSocketShard.onMessage (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z
ode_modules\discord.js\src\client\websocket\WebSocketShard.js:317:10)
    at WebSocket.onMessage (C:\Users\smonf\OneDrive\Bureau\Bots Discord\New Projects\- MyCorp\archive-2022-06-25T114850Z
ode_modules\ws\lib\event-target.js:199:18)"
}

How to Check multiple element class with jQuery or CSS

How can I change the number of element tc4?
When the previous two elements had a hidden class.

this my code:

<style>
:before{
    display:block;
    margin-top:10px;
    font: inherit;
}
.tc-hidden{
    display:none;
}
.tc1 h3.tm-section-label:before {
    content: "1";
}
.tc2 h3.tm-section-label:before {
    content: "2";
    
}
.tc3 h3.tm-section-label:before {
    content: "3";
}
.tc4 h3.tm-section-label:before {
    content: "4";
}
.tc2.tc-hidden ~ .tc3 h3.tm-section-label:before {
    content: "2";
    font: inherit;
}
.tc3.tc-hidden ~ .tc4 h3.tm-section-label:before {
    content: "3";
    font: inherit;
}
.tc2.tc-hidden .tc3.tc-hidden ~ .tc4 h3.tm-section-label:before {
    content: "2";
    font: inherit;
}

</style>
  <div class="tc-cell tc1">
        <h3 class="tm-section-label"></h3>
    </div>
    <div class="tc-cell tc2 tc-hidden">
        <h3 class="tm-section-label"></h3>
    </div>
    <div class="tc-cell tc3 tc-hidden">
        <h3 class="tm-section-label"></h3>
   </div>
   <div class="tc-cell tc4">
        <h3 class="tm-section-label"></h3>
   </div>

TC4 element must show the number 2.
But now it shows the number 3.

It doesn’t matter if this code is done with css or jQuery.

Why i can’t retreive data from object JavaScript [closed]

What i am trying to do is to access a value from my object.
const body = req.body.order

const body = req.body.order

return:

{
  id: '02',
  name: 'TREX',
  size: '20x20(CM)',
  pixels: '450',
  price: '40',
  author: 'RUGXY',
  picture: './JSON/image/snowman.svg'
}

What i try to output

  console.log(body.name)

should output:

'TREX'

outputs:

C:xampphtdocsserver.js:10
  console.log(body.name)
                   ^

TypeError: Cannot read properties of undefined (reading 'name')
    at C:xampphtdocsserver.js:10:20

Additional:

console.log(typeof(body))
object

here is the code that sends the data to post request

    const createUserInfo = (form) =>{
    let personalInformation = {}

    for (var p of form) {
        let name = p[0];
        let value = p[1];
        personalInformation[name.replace(/cout-/gm, '')] = value
    }
    return personalInformation
}

const retriveOrder = () =>{
    let orderInfo = JSON.parse(localStorage.getItem("cart_item"));
    return orderInfo;
}


document.querySelector('#checkout').onsubmit= async e =>{
    const form = new FormData(document.querySelector('#checkout'))
    let user = createUserInfo(form),
        order = retriveOrder()

    fetch("/checkout/create-order", {
        method: "POST",
        mode: "same-origin",
        redirect: 'manual',
        headers:{
            "Content-Type": "application/json"
        },
        body: JSON.stringify(
            {
                order: order,
                user: user
            }
        )
    }).then(res=>{
       res.ok
    }).then(data=>{
        console.log(data)
    })
}

Uncaught TypeError: Cannot read properties of undefined (reading ‘call’) – webpack.require

Can anyone please help me in resolving this issue?

Error image

Webpack.config.js :

module.exports = {
  devtool: isProdEnv ? "source-map" : "eval",
  entry: "./lib/index.ts",
  mode: isProdEnv ? "production" : "development",
  watch: isWatchEnv,
  target: "node",
  externals: [
    nodeExternals({
      allowlist: ["node-fetch"],
    }),
  ],
  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: ["ts-loader"],
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    fallback: {
      buffer: require.resolve("buffer"),
      stream: require.resolve("stream-browserify"),
    },
  },
  output: {
    filename: path.basename(pkg.main),
    path: path.resolve(cwd, "dist"),
    libraryTarget: "commonjs2",
  },
  plugins,
  optimization: {
    usedExports: true, // TODO: how to enable tree shaking on commonjs internal and modules? tsconfig should be esnext?
  },
};

tsconfig.json:

“compilerOptions”: {
“module”: “commonjs”,
“declaration”: true,
“allowSyntheticDefaultImports”: true,
“esModuleInterop”: true,
“noImplicitAny”: true,
“noImplicitThis”: true,
“noUnusedLocals”: true,
“target”: “es5”,
“sourceMap”: true,
“moduleResolution”: “node”,
“resolveJsonModule”: true,
“skipLibCheck”: true,
“lib”: [“es2017”, “es7”, “es6”, “dom”, “es2015”],
“baseUrl”: “./packages” },

get the higher num of array of object of array react

hello i have a question.
i need to get the 3 object that has the highest rating (for now i have 3 by it dosent matter because i need to add more)
how can i do it?
i am trying to use sort and spread
but because that is array of object and another array (rating)
i get confused
thanks

  const [movies, setMovies] = useState([
{
  movieName: "godfather",
  info: "the rise of  corelone family  all mater is respect,money,woman but the youngest son michal has a diffrent plans...",
  picture: "pictures/godfather.jpg",
  rating: [10, 5, 1],
},
{
  movieName: "scarface",
  info: "the rise of  tony montata the badass man of miami want to control miami and be the number 1 of the cocaine provider ...",
  picture: "pictures/scarface.jpg",
  rating: [10, 9, 2],
},
{
  movieName: "the-dark-knight",
  info: "you all knew that he will come the batman! come to fight with his popular rival the joker...",
  picture: "pictures/the-dark-knight-poster.jpg",
  rating: [10, 10, 9],
},

]);

React firebase database order by date

I’m making a todo list app using react and firebase realtime database.

I want to get the todos ordered by date.

My Database: photo

And if I cant do this from firebase, is there a way to order it from the client side (react)?

My Code

Todos.js:

import { useState, useEffect } from "react";
import { signOut, onAuthStateChanged } from "firebase/auth";
import { uid } from "uid";
import { set, ref, onValue } from "firebase/database";
import { auth, db } from "../firebase";
import moment from "moment";

function Todos() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState("");
  const navigate = useNavigate();

  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        onValue(ref(db, `/${auth.currentUser.uid}`), (snapshot) => {
          setTodos([]);
          const data = snapshot.val();
          if (data !== null) {
            Object.values(data).map((todo) => {
              setTodos((currentTodos) => [todo, ...currentTodos]);
            });
          }
        });
      } else {
        navigate("/");
      }
    });
  }, []);

  const handleSignOut = () => {
    signOut(auth)
      .then(() => navigate("/"))
      .catch((error) => alert(error.message));
  };

  const addTodo = () => {
    const uidd = uid();
    set(ref(db, `${auth.currentUser.uid}/${uidd}`), {
      task: newTodo,
      uid: uidd,
      createdAt: moment().format("YYYY-MM-DD k:m:s"),
    });

    setNewTodo("");
  };

  return (
    <>
      <Center>
        <Button colorScheme="red" marginTop={5} onClick={handleSignOut}>
          Logout
        </Button>
      </Center>
      <Container
        maxW="4xl"
        marginTop={8}
        display="flex"
        alignItems="center"
        justifyContent="center"
      >
        <Box
          boxShadow="base"
          rounded="lg"
          padding={10}
          background="white"
          width="100%"
        >
          <Heading as="h1" size="md" textAlign="center">
            Todo List App
          </Heading>
          <form onSubmit={(e) => e.preventDefault()}>
            <Box
              display="flex"
              alignItems="center"
              justifyContent="space-between"
              marginTop={5}
            >
              <Input
                placeholder="New Task"
                value={newTodo}
                onChange={(e) => setNewTodo(e.target.value)}
                size="lg"
                width="80%"
              />
              <Button
                colorScheme="teal"
                height={45}
                rightIcon={<MdAdd />}
                margin={0}
                onClick={addTodo}
                type="submit"
              >
                Add
              </Button>
            </Box>
          </form>
          {todos.map((todo, index) => {
            return <Todo key={index} task={todo.task} uid={todo.uid} />;
          })}
        </Box>
      </Container>
    </>
  );
}

export default Todos;

Thanks in advance.

React: added product changes it’s attributes after I add another product with different attribute while on the same product page

So let’s say you are on the product page of a Nike T-shirt, you choose the color and size(eg:black and S) and add it to cart. Now the cart contains 1 Nike T-SHIRT with selectedAttributes: color: black, size: s. Now, while on the same T-shirt page, you choose color white and size M, the previous added T-shirt’s attributes change from (color:black into color: white, and form size:s into size:M) and now you have in cart 2 T-SHIRTS SIZE :M AND COLOR: BLACK. What am I doing wrong?

class PDP extends Component {
      state = {
        currentProduct: this.props.location.state,
        selectState: [],
        testObj: {},
      } 
    render() {
    let product = this.state.currentProduct;
    let handleChange = (evt,attribute) => {
            const test = Object.assign({}, product);
            this.state.testObj[attribute] = evt.target.value;
            this.state.selectState.push(this.state.testObj);
            let selectedAttributes = [...new Set(this.state.selectState)];
            test.selectedAttributes = selectedAttributes;
            this.setState((state) => ({
              currentProduct: test
            }))
          } 
    
    <button className="addToCart" onClick={() => this.props.data.addProduct(this.state.currentProduct)}>ADD TO CART</button>
    
     addProduct = (product) => {
        this.setState((state) => ({
          cart: state.cart.concat(product),
        }))
       
      } 

Vue.js how to get state properties of pinia?

i want to get my state from pinia , and can not do this, i don’t know what i have to text in the value (like this.username or something) to get my map state values… (screen added), i use options api, and vue 3.
i got undefined in the console by the way
enter image description here

What is the running time of this algorithm from ‘Introduction to Algorithms/CLRS’?

Problem 2.3-7 of the “Introduction to Algorithms/CLRS” book: Describe a ϴ(nlgn)-time algorithm that, given a set S of n integers and another integer x, determines wheter or not there exist two elements in S whose sum is exactly x.

My solution to the problem involves both merge sort and binary search, my calculations show that it’s running time is ϴ(nlgn), but they may be faulty, so I need your affirmation, here it is:

function findPair(arr, x) {
    mergeSort(arr, 0, arr.length - 1);

    for (let i = 0; i < arr.length - 1; ++i) {
        let b = binarySearch(arr, x - arr[i], i+1);
        if (b) {
            return true
        }    
    }

    return false;
}

Here is my thought process: merge sort has a running time of ϴ(nlgn), and it is run once, binary search has a running time of ϴ(lgn), and it is run (n-1) times, and so it contributes to ϴ(nlgn) to the total running time, therefore the total running time of the algorithm is ϴ(nlgn).

I would like to see if I am right, and if not, I’d like to see your suggestions.

React: Uncaught TypeError: animes.map is not a function

I’m new to React and I’m doing an Anime project. I’ve managed to get the values of the animes from the Jikan API with the map function. But the url’s correspond to for example “https://api.jikan.moe/v4/genres/anime” or “https://api.jikan.moe/v4/top/anime?filter=bypopularity”, but if i change that same url to a specific character (for example: “https://api.jikan.moe/v4/people/5579”) or a specific movie (for example “https://api.jikan.moe/v4 /anime/38000”) tells me that “animes.map is not a function”. I’ve verified that the parameters are correct. I would appreciate your help.


const getAnimes = async () => {
  try {
    const response = await fetch('https://api.jikan.moe/v4/people/5579');
    const animes = await response.json();
    return animes;
  } catch (error) {
    console.error(error);
  }
};

function App() {
  const [animes, setAnimes] = useState([]);

  const fetchAnimes = async () => {
    try {
      const data = await getAnimes();
      setAnimes(data.data);
    } catch (error) {}
  };

  useEffect(() => {
    fetchAnimes();
  }, []);

  return (
    // <React.Fragment>
    <>
      <header>
        <h1>Search Anime</h1>
      </header>
      <main>
        <article className="countries">
          {animes.map((anime) => (
            <div key={anime.mal_id}>
              <h2>{anime.name}</h2>
            </div>
          ))}
        </article>
      </main>
    </>
    // </React.Fragment>
  );
}

export default App;```

How to show RSS ATOM Feed in HTML

I have a HTML website and I want to show th weather.gov ATOM Rss feed on it but i don’t know how to do it. I searched in the internet but didn’t find any solution. Does someone know how I could do this? Thanks for your answer 😀

Get distance between two markers in react-leaflet

I have two variables:

const userPos = { lat: 68.39918004344189, lng: -55.54687500000001 }
const solution = { lat: 58.722598828043395, lng: -36.92504882812501 }

I need to get the distance between the two. What I tried was:

userPos.distanceTo(solution)

Also:

distanceTo(userPos, solution)

Also:

const userPosLng = userPos.lng
userPosLng.distanceTo(solution.lng) //tried both with .lat as well

and finally:

const userPosLng = userPos.lng
distanceTo(userPosLng, solution.lng)

None of these worked, and only these were what I found in the documentation and on the internet.
So I am now out of ideas, and I would appreciate some help.

How to prevent react router 5 to render DashboardLayout component below specific route?

I am trying to create a route that works as follows:

 <Route path='/home' exact component={Home}/>
{loggedin &&
<DashboardLayout>
<Route path='/settings' exact component={Settings} />
<Route path='/edit' exact component={AdMaker} />
</DashboardLayout>
}

If I am logged in, the DashboardLayout is rendering which I dont want if the route is /home. What should i do? [Please recommend methods other than switch]