Which is better performance-wise: inline styles vs. inline styles with variables vs ref [closed]

For the past few days, I have been trying to understand best practices for better performance for react applications. I read that inline styles are not as efficient as CSS class-based styles for obvious reasons but I wanted to know how much they actually differ when compared to:

  1. Inline styles with variables
    example:
<div id='myDiv' style={ "--myColor": dynamic_color }></div>`

CSS:

#myDiv {
 color: var(--myColor)
}
  1. Element References
    example:
divRef.current.style.background = dynamic_background

Considering performance, which one of them is the best and which one should be used in what cases. Also, is there any other way that might be more suitable for dynamic styles.

Thanks

Add images On Radar Chart Labels in ChartJS 4

I am trying to add images instead of the default label on the chart, like in the example i am trying to set eating… to a custom image labels

I tried following the official doc.

https://www.chartjs.org/docs/latest/charts/radar.html

const data = {
  labels: [
    'Eating',
    'Drinking',
    'Sleeping',
    'Designing',
    'Coding',
    'Cycling',
    'Running'
  ],
  datasets: [{
    label: 'My First Dataset',
    data: [65, 59, 90, 81, 56, 55, 40],
    fill: true,
    backgroundColor: 'rgba(255, 99, 132, 0.2)',
    borderColor: 'rgb(255, 99, 132)',
    pointBackgroundColor: 'rgb(255, 99, 132)',
    pointBorderColor: '#fff',
    pointHoverBackgroundColor: '#fff',
    pointHoverBorderColor: 'rgb(255, 99, 132)'
  }, {
    label: 'My Second Dataset',
    data: [28, 48, 40, 19, 96, 27, 100],
    fill: true,
    backgroundColor: 'rgba(54, 162, 235, 0.2)',
    borderColor: 'rgb(54, 162, 235)',
    pointBackgroundColor: 'rgb(54, 162, 235)',
    pointBorderColor: '#fff',
    pointHoverBackgroundColor: '#fff',
    pointHoverBorderColor: 'rgb(54, 162, 235)'
  }]
};

new Chart("myChart", {
type: 'radar',
  data: data,
  options: {
    elements: {
      line: {
        borderWidth: 3
      }
    }
  },

});

plugin:vite:import-analysis Failed to resolve import “./components/Buttons” from “srcpagesCalculator.jsx”. Does the file exist?

I am trying to import Buttons from components folder to the pages folder Calculator.jsx file. But I am getting an error “[plugin:vite:import-analysis] Failed to resolve import “./components/Buttons” from “srcpagesCalculator.jsx”. Does the file exist?”

I trying to import Buttons component to use it in calculator.jsx file located in pages folder

explaining why React Hook useEffect has a missing dependency

I’m new to React, but why vs code is showing me this message in the problem tab
isn’t adding currentNoteId to the dependence array will crash the app

  const [notes, setNotes] = useState([]);
  const [currentNoteId, setCurrentNoteId] = useState("");

  useEffect(() => {
    if (!currentNoteId) {
      setCurrentNoteId(notes[0]?.id);
    }
  }, [notes]);

React Hook useEffect has a missing dependency: ‘currentNoteId’. Either include it or remove the dependency array.

I tried what vs code was suggesting but did not understand why, if you can tell me what’s going on please

Shopify Version Porto Theme Ver 3.6.1, Need add to cart redirect to cart page with checkout option instead of staying on product page

I am not quite yet a full developer, but am working on a website that sells products.

The customer clicks a product

They see the product information, and after selecting a size, they click add to cart

After clicking add to cart, it notifies them that they added to cart with a quick splash saying (you’ve just added this to your cart) for a quick second, and then you have a choice of either going to cart, or continue shopping, but it quickly goes away.

We would like for it to just redirect to product page, with the added product once they add it to their cart. How would I do this?

I tried going through some of the store code, but it is a bit over my head.

I tried asking chatgpt but they gave me a pretty broad way of how I would supposedly do it.

Going to ask Shopify next, but figured I’d ask the dev community to find a quicker fix.

All i need for it to do is just redirect to the customers cart once they’ve added it to the cart (and would love for that product to also simultaneously be in their cart as they are going to it if that was not obvious)

Cors error with vannila JS and Spring Boot

Hy, i have this problem, i want to call and enpoint made with spring boot. The endpoint is secured by spring security and show me a CORS error:

This is the spring security setting

@Bean
        public SecurityFilterChain filterChain(@NotNull HttpSecurity http) throws Exception {
            http
                    .cors(AbstractHttpConfigurer::disable)
                    .csrf(AbstractHttpConfigurer::disable)
                    .exceptionHandling(
                            httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(this.unauthorizedHandler)
                    )
                    .sessionManagement(
                            httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    )
                    .authorizeHttpRequests(
                            authorizationManagerRequestMatcherRegistry ->
                                    authorizationManagerRequestMatcherRegistry
                                            .requestMatchers("/api/v1/auth/**").permitAll()
                                            .anyRequest().authenticated()
                    );
            http.addFilterBefore(this.authTokenFilter, UsernamePasswordAuthenticationFilter.class);
            return http.build();
        }

this is the js code:

let ajaxUsername = new XMLHttpRequest();
    ajaxUsername.withCredentials = true;
    ajaxUsername.open("POST", apiBaseUrl + "api/v1/user-info/retrieve-username");
    ajaxUsername.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("jwt"));
    //ajaxUsername.setRequestHeader("Access-Control-Allow-Origin", "http://localhost");
    ajaxUsername.send();
    ajaxUsername.onreadystatechange = function () {
        if (this.readyState === 4) {
            console.log(this);
        }
    }

and this is the controller that manage the request:

@RestController
@RequestMapping("/api/v1/user-info")
@CrossOrigin(origins = "http://localhost")
public class UserInfoControllerImpl implements UserInfoController {
    private final JwtUtils jwtUtils;

    @Autowired
    public UserInfoControllerImpl(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public ResponseEntity<String> retrieveUsername(String authorization) {
        return null;
    }
}

in the browser console appear this error: Access to XMLHttpRequest at 'http://localhost:8080/api/v1/user-info/retrieve-username' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The endpoint with permitAll() in spring boot work well without issue, but the other that require jwt token show the CORS error, and i cant figure out what is the problem. Can anyone help me?

Error when tried to install react_router_dom

When i tried to install react-router-dom

i got this error:

Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:68:19)
at Object.createHash (node:crypto:138:10)
at module.exports (D:Programmingpcbuildersitenode_moduleswebpacklibutilcreateHash.js:135:53)
at NormalModule._initBuildHash (D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:417:16)
at handleParseError (D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:471:10)
at D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:503:5
at D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:358:12
at D:Programmingpcbuildersitenode_modulesloader-runnerlibLoaderRunner.js:373:3
at iterateNormalLoaders (D:Programmingpcbuildersitenode_modulesloader-runnerlibLoaderRunner.js:214:10)
at iterateNormalLoaders (D:Programmingpcbuildersitenode_modulesloader-runnerlibLoaderRunner.js:221:10)
D:Programmingpcbuildersitenode_modulesreact-scriptsscriptsstart.js:19
throw err;
^

Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:68:19)
at Object.createHash (node:crypto:138:10)
at module.exports (D:Programmingpcbuildersitenode_moduleswebpacklibutilcreateHash.js:135:53)
at NormalModule._initBuildHash (D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:417:16)
at D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:452:10
at D:Programmingpcbuildersitenode_moduleswebpacklibNormalModule.js:323:13
at D:Programmingpcbuildersitenode_modulesloader-runnerlibLoaderRunner.js:367:11
at D:Programmingpcbuildersitenode_modulesloader-runnerlibLoaderRunner.js:233:18
at context.callback (D:Programmingpcbuildersitenode_modulesloader-runnerlibLoaderRunner.js:111:13)
at D:Programmingpcbuildersitenode_modulesbabel-loaderlibindex.js:59:103 {
opensslErrorStack: [ ‘error:03000086:digital envelope routines::initialization error’ ],
library: ‘digital envelope routines’,
reason: ‘unsupported’,
code: ‘ERR_OSSL_EVP_UNSUPPORTED’
}

I already tried to update npm. That error appear when i tried to install react-router-dom

Multiple dropdown menus opening all at once

I built a “dropdown menu” that allows my content to be hidden until onclick event with HTML, CSS, and JS. However, the menus all open at the same time when one menu is clicked. I want only one menu to open at a time.

here’s my code so far:

HTML

<div class="hidden">
  <button id="myFunction()" class="dropbtn">Title of Section</button>
  <div id="myDropdown" class="hidden-content">
  <div class="article-list">
              
  </div>
  </div>
  </div>

I have multiple of these “hidden” divs, each named the same thing so the same effects work on them in my CSS. There’s about 5 of them I believe. I put the hidden content inside “hidden-content” and have removed the irrelevant sections that don’t matter to the code question. If there’s something I’m missing, let me know and I’ll do my best to update.

CSS

.dropbtn {
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  width: 100%;
  font-family: 'Turret Road';
  font-size: 35px;
  font-weight: 600;
  color: var(--default5);
  text-align: center;
  border-radius: 15px;
  background-image: linear-gradient(var(--defaultAccent1), var(--default3Muted));
  box-shadow: var(--default1) 3px 3px 3px 3px;
}

.dropbtn:hover, .dropbtn:focus {
  background-image: linear-gradient(var(--defaultAccent1), var(--default1));
}

.hidden {
  position: relative;
  display: inline-block;
}

.hidden a:hover {
  background-image: linear-gradient(var(--defaultAccent1), var(--default1));
}

.hidden-content {
  display: none;
  position: relative;
  right: 0;
  width: 100%;
  background-color: var(--default3Muted);
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
  border-radius: 15px;
}

.show {
  display: block;
}

.hidden-content a {
  color: var(--default1);
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

The CSS all seems to be working, but the JS requires a “show” element that I have not put into the HTML at all. It still functions without it. Do I need to add the “show” element to my HTML?

JS

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("hidden-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

What am I doing wrong?

One DAO per entity vs multiple DAO’s per entity

Sorry for the long question. I have tried my best to articulate my thoughts as best I can. I am slightly confused with the common practice I hear of one repository per entity. Does this mean we have a Dao class which targets a specific entity whether that entity be a table or a column in our sql database ?

Won’t this Dao class then have multiple methods where only 1 or a subset of methods are used during different events ( requests from the client) especially if some of my business logic is done on the database using joins and sub queries. Only a subset of these methods could be used at any one time depending on the event that takes place.

In my game of monopoly for example I have a Dao class which targets the players money which consists of this :

module.exports = class PlayerMoneyDAO {
constructor() {}

static async deductMoneyFromPlayer(amount, playerId, connection {
 // this simpler method is normally called when completing more logic within the app server 
  try {
    await connection.execute(`UPDATE players SET Money = money - (?) WHERE id = (?) `, [amount, playerId]);
  } catch (e) {
  throw new Error("server problem with deducting a players money on the database");
  }
}

static async addMoneyToPlayer(amount, playerId, connection) {

  try {
    await connection.execute(`UPDATE players SET Money = money + (?) WHERE id = (?) `, [amount, playerId]);
  } catch (e) {
  throw new Error("Failed to inccrease the money for the receiving player");
  }
}

static async moneyAdjustmentToPayStationRent(connection) { // this is they type of logic I do in the database server so the queries tend to be more complex
  try {
    await connection.execute(`UPDATE stations as stationLanded
    INNER JOIN board ON stationLanded.board_id = board.id
    INNER JOIN players as playerLanded ON playerLanded.board_id = board.id
    INNER JOIN game_logic ON playerLanded.id = game_logic.player_turn
    INNER JOIN players as playerOwner ON stationLanded.owner_id = playerOwner.id
    INNER JOIN stations_rent
    set playerOwner.money = CASE WHEN playerLanded.money >= stations_rent.rent_price THEN playerOwner.money + stations_rent.rent_price
    else playerOwner.money end,
    playerLanded.money = CASE WHEN playerLanded.money >= stations_rent.rent_price THEN  playerLanded.money - stations_rent.rent_price
    else playerLanded.money end
    WHERE stations_rent.number_of_stations_owned = (
      SELECT count(id) from stations WHERE owner_id = stationLanded.owner_id);`);
  } catch (e) {
  throw new Error("player money updates failed when landing on an owned station");
  }
}

static async moneyAdjustmentToPayPropertyRent(connection) {
  try {
    await connection.execute(`UPDATE players AS playerLander
    INNER JOIN game_logic ON playerLander.id = game_logic.player_turn
    INNER JOIN board ON playerLander.board_id = board.id
    INNER JOIN properties ON properties.board_id = board.id
    INNER JOIN rent ON rent.property_id = properties.id
    INNER JOIN players as playerOwner ON properties.owner_id = playerOwner.id 
    SET playerLander.money = CASE WHEN playerLander.money >= rent.rent_price THEN    playerLander.money - rent.rent_price
    else playerLander.money end,
    playerOwner.money = CASE WHEN playerLander.money >= rent.rent_price THEN playerOwner.money + rent.rent_price
    else playerOwner.money end
    WHERE properties.rent_price_point = rent.rent_price_point_value;`);
  } catch (e) {
  throw new Error("player money updates failed when landing on an owned property");
  }
}
 static async checkIfUpdatesOccured(connection) {
  const result = await connection.execute("SELECT ROW_COUNT() AS affected_rows");
  return result[0][0].affected_rows;
}

 static async getMoneyOfPlayerWhomHasJustReceivedPayment(connection, id) { 
    try {
      const result = await connection.execute(`SELECT money,piece FROM players   WHERE id = (?)`, [id]);
  return result[0][0];
    } catch (e) {
      throw new Error("couldnt get the updated money of the player that was piad money so no transaction has taken place");
   }
 }

static async getMoneyUpdatesAfterRentPaid(connection, tableName) {
  const result = await connection.execute(`SELECT piece,money FROM players WHERE id = (
    SELECT player_turn FROM game_logic) 
    UNION
    SELECT playerOwner.piece, playerOwner.money FROM ${tableName}
    INNER JOIN board ON board.id = ${tableName}.board_id
    INNER JOIN players ON players.board_id = board.id 
    INNER JOIN game_logic ON players.id = game_logic.player_turn
    INNER JOIN players AS playerOwner WHERE ${tableName}.owner_id = playerOwner.id`);

   return result[0];
   }
 };

There are still some methods to be added. This Dao’s methods all target the same entity ( the players money) column.

I also have service objects which provide methods that depend on the DAO passed into the service object.
The higher level mediator class has various service objects dependancies and contains the business logic of when to call methods from each service class. Each service class methods when called from the mediator access the Dao dependancy within the service object and invokes methods from it.Each Service object Dao dependancy represents the one repository per entity theory and has all the methods inside that Dao that target the players money column within the players table.

A service object example may be named something like RentPaymentManager and receives the the PlayerMoneyDAO as a dependancy. Here we only need access to the moneyAdjustmentToPayPropertyRent and getMoneyUpdatesAfterRentPaid methods. These service objects are event specific rather than have generic methods like the DAO is. Some of these service objects only contain the one method which invokes a single method from the DAO dependancy. Some the service objects may need to call 2-3 methods from the DAO like this RentPaymentManager service object. If there is a service object that includes a method I want to re use then I put this into its own class and inherit from it or use it within the composition of my larger object. However at this time each event specific service object still receives the PlayerMoney Dao in full which consists of all methods which access the database. My Service objects often dont need all the methods from the DAO but only 1 or a sub set of those methods as explained. Before I was binding DAO methods to a specific service object when instantiating the service object so it only includes methods that it actually needs from the DAO. I was even creating a generic service object which just invoked the corresponding DAO method.

Now I’m thinking should I create various different Dao repositories classes for each event that occurs or shall I stick to only having one repository class per entity and allow my event specific service object to decide what it needs from the Dao by providing methods that access the Dao ( which is now a dependancy ) from the service object? For example my RentPatmentManager class could no longer have the full single repository for the players money but instead have a DAO specific to the event that has occurred? However If I do this suddenly I have multiple repositories per entity because all the DAO classes are now event specific rather than a generic single repository. Or should me RentPaymentManager class still just receive the one DAO which would be the same DAO passed to all event specific service classes ?

So what I am asking is shall I create an inheritance hierarchy or composite hierarchy in my service class but my Dao’s that are passed into the service classes remain generic ? If I dont do it this way and gave multiple DAO’s targeting the same entity then suddenly I have more than one repository per entity which goes against the advice I have received in the past ?

ajax load more show and hide if all post loaded – WordPress

I have some alpine.js script and ajax that is loading more wordpress post on click of a button, this is working well.

however I am now trying to add some code to the button to hide if no post available to load, im doing this with my button by adding

x-show="total > (limit + offset)".

my limit is 6 and offset is null and post count is 10 so it should show the button, however its hidden.

im thinking it could be my getTotal()is not correctly getting my total setting the button to be hidden.

any insight a or help with this is much appreciated, once again if I remove

x-show="total > (limit + offset)" 

my button shows and loads more post, but I am trying to get it to hide or show depending if more post available.

Bellow is my Alpine.js, AJAX and html/php wordpress code

Im expecting button to hide if no more post are avalible to load.

I tried this with the gettotal function and x-show in the alpine.js

alpine

<script>
Alpine.data("filterPosts", (adminURL) => ({
    posts: "",
    limit: 6,
    total: null,
    category: null,
    post_type_js: post_id,
    showDefault: true,
    showFiltered: false,
    offset: null,
    
    filterPosts(id) {
        this.showDefault = false;
        this.showFiltered = true;
        this.category = id;
        this.offset = 0; // <-- reset offset to zero
        this.fetchPosts();
    },
    
     loadMore() {
        this.loadingMore = true;
        this.offset += 6;
        this.showFiltered = true;
        this.fetchPosts(true);
    },

    fetchPosts(append = false) {
        var formData = new FormData();
        formData.append("action", "filterPosts");
        formData.append("limit", this.limit);
        formData.append("post_type_js", this.post_type_js);
        formData.append("offset", this.offset); // <-- Add new data to the form

        if (this.category) {
            formData.append("category", this.category);
        }

    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
            if (append) {
                // Appends posts to the end of existing posts data
                this.posts = this.posts.concat(res.posts);
            } else {
                // Resets the posts data with new data
                this.posts = res.posts;
            }

            this.loading = false;
        });
    },
    
    getTotal() {
    var formData = new FormData();
    formData.append("action", "filterPosts");

    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
        this.total = res.total;
    });
},

init() {
    this.getTotal();
}

}));
})
     </script>

wordpress php

<body>
        <div x-data="filterPosts('<?php echo admin_url('admin-ajax.php'); ?>')">
    <section <?php theme_section_attr_id() ?> <?php theme_section_attr_class('main-section js-posts') ?>>
      <div class="container">
        <div class="heading mx-0">
          <?php $before_title = get_sub_field('before_title');
          if ($before_title) : ?>
            <strong class="sub-title"><?php echo $before_title ?></strong>
          <?php endif ?>
          <?php $title = get_sub_field('title');
          if ($title) : ?>
            <h2><?php echo $title ?> </h2>
          <?php endif ?>
        </div>
    
          <div class="head js-posts-search-text">
            <?php if ($search_value) : ?>
              <h2 class="h5 fw-semibold"><?php printf(__('Showing results for “%s”', 'base'), $search_value) ?></h2>
            <?php endif ?>
          </div>
          
    <!--alipne js dynamic post start-->
        <div class="has-filter row flex-md-row-reverse">
            <div class="col-md-8 col-lg-9 js-posts-holder">
                
            <!-- Posts Column -->
                <div x-show.important="showDefault" class="row cards-area js-posts-items">
                    <!-- Default posts query -->
                    <?php get_template_part( 'template-parts/posts-filter/default-query' ); ?>
                </div>
                    <!-- Filtered posts -->
                <div x-show.important="showFiltered" x-html="posts"class="row cards-area js-posts-items">
                </div>
                <!-- Load More Posts -->
                
           <!-- Load More Posts -->
    <div @click="loadMore()" x-show="total > (limit + offset)"  class="text-center mt-12 pt-5">
        <button class="">
            Load More
        </button>
    </div>
             </div>
                
            <!-- Filtered posts -->
            <div class="col-md-4 col-lg-3">
                 <?php get_template_part( 'template-parts/posts-filter/filter-query' ); ?>
            <!-- Filtered end -->
             </div>   
        </div>
        </div>
    <!--alipne js dynamic post end-->
    
    </section>
    </div>
    </body>

Ajax

// the ajax function
add_action('wp_ajax_filterPosts', 'filterPosts');
add_action('wp_ajax_nopriv_filterPosts', 'filterPosts');

function filterPosts()
{
    $response = [
        'posts' => "",
    ];
        // New args for an All Posts Query
    $all_args = array(
        'posts_per_page' => -1, // returns all posts
        'post_status' => 'publish',
    );
    
    $filter_args = array(
        'post_status' => 'publish',
    );
    
    if (isset($_POST['offset'])) {                      
    $filter_args['offset'] = max (0, (int)$_POST['offset']);
    }

    if ($_POST['limit']) {
        $filter_args['posts_per_page'] = $_POST['limit'];
    }
    
     if ($_POST['post_type_js']) {
        $filter_args['post_type'] = $_POST['post_type_js'];
    }

    if ($_POST['category']) {
        $filter_args['cat'] = $_POST['category'];
        
        // Get the total number of posts for the category
        $all_args['cat'] = $_POST['category'];

    }

    $filter_query = new WP_Query($filter_args);
    
    // New All Posts Query
    $all_query = new WP_Query($all_args);

    

    if ($filter_query->have_posts()) :
        while ($filter_query->have_posts()) : $filter_query->the_post();
            $response['posts'] .= load_template_part('/template-parts/posts-filter/single-post');
        endwhile;
        wp_reset_postdata();
    endif;

    echo json_encode($response);
    die();
}


function load_template_part($template_name, $part_name = null, $args = [])
{
    ob_start();
    get_template_part($template_name, $part_name, $args);
    $var = ob_get_contents();
    ob_end_clean();
    return $var;
}

Parse parameters/values from JSON API query with JavaScript

How do I parse a JSON API style query in JavaScript? An example query would be:

/search?filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary

I want to extract the filter fields and value (and ideally other JSON API parameters). I don’t mind too much what format the result is in, whether it’s an oject or array etc. I need to be able to check if a filter exists and get it’s value.

Happy to use a library is there is one, but can’t find one.

How to create a resizable and movable div in wrapper div in react.js?

This is what I need:
enter image description here

enter image description here

So, this lightblue div needs to be:

  • resizable (on the left and right side, cannot resize over lightgray wrapper div width), and
  • movable inside lightgray wrapper div (cannot overflow its sides).

On his sides, lightblue div needs to have cursor: ew-resize; and inside needs to be cursor: grab.

I tried so many things but I didnt success to do both functionalities, I have separately resizing and movable… Also, I don’t use any library for it.

How to achieve that in js and react.js?

Please help if someone know!

React – SWR – no update component

I know i’m going to feel very stupid but here goes. I have been learning React for a couple of weeks now (coming from all native javascript client side) and I have been fetching data using useEffect. But i’m seeing more and more remarks to avoid this and use SWR instead. But the component does not show the received data. I know this is going to be something simple but after multiple hours searching i’m giving up and asking the question: What prevents this component from updating on recieving data?

const MissieDetail = () => {

const { data: missions, isLoading, error } =
    useSWR('GetMissions', GetMissions, {
        onSuccess(data, key, config) {
            console.log(data)
        }
    })
let content
if (isLoading) { content = <p>Loading...</p> }
if (error) { content = <p>{error.message}</p> }
content =
    <ul>
        {
            missions.map((mission) => {
                <li key={mission.id}>{mission.titel}</li>
            })
        }
    </ul>
return (
    <main>
        <h2>Mission List</h2>
        {content}
    </main>
)}

I am receiving data. At that moment the “loading” message disappears but no li are added to the ul
enter image description here

How add elements from one object to another object, all objects exist in on array

I need from this:

const initialArray = [
  {
    unitId: 28102,
    unitFilter: {
      extras: [
        {
          id: 100,
          extraType: "BEDROOM",
        },
        {
          id: 1,
        },
      ],
    },
    accommodationId: 18996,
  },
  {
    unitId: 28103,
    unitFilter: {
      extras: [
        {
          id: 2,
        },
      ],
    },
    accommodationId: 18996,
  },
  {
    unitId: 54517,
    unitFilter: {
      extras: [
        {
          id: 101,
          extraType: "BEDROOM",
        },
        {
          id: 3,
        },
      ],
    },
    accommodationId: 18952,
  },
  {
    unitId: 55705,
    unitFilter: {
      extras: [
        {
          id: 4,
        },
      ],
    },
    accommodationId: 18952,
  },
];

get this:

const resultArray = [
  {
    unitId: 28102,
    unitFilter: {
      extras: [
        {
          id: 100,
          extraType: "BEDROOM",
        },
        {
          id: 1,
        },
      ],
    },
    accommodationId: 18996,
  },
  {
    unitId: 28103,
    unitFilter: {
      extras: [
        {
          id: 2,
        },
        {
          id: 100,
          extraType: "BEDROOM",
        },
      ],
    },
    accommodationId: 18996,
  },
  {
    unitId: 54517,
    unitFilter: {
      extras: [
        {
          id: 101,
          extraType: "BEDROOM",
        },
        {
          id: 3,
        },
      ],
    },
    accommodationId: 18952,
  },
  {
    unitId: 55705,
    unitFilter: {
      extras: [
        {
          id: 4,
        },
        {
          id: 101,
          extraType: "BEDROOM",
        },
      ],
    },
    accommodationId: 18952,
  }

I want to add elements with extraType: “BEDROOM” (if it doesn’t exist) to unitFilter.extras, each object matches the accommodationId.

So, every Object with same accommodationId must have unitFilter.extras with extraType: “BEDROOM”.

P.s.: it would be cool, if it can be implemented with .reduce or something actual =)

Calculate 2 balance points of a random mesh

I have flat models of random island shapes, how can I calculate the 2 optimal balance points as if it was a table with 2 sturdy legs? I understand it could be possible to find a single average center/balance point of a shape with 1 balance point, but how can I make it into 2 points?

Thankful for help in any direction!