How can I change pages when searching by id for an element in a table? Vue js

I have a problem, I work with vue js, vuetify2, I have a table of elements with a pagination, currently there are 2 pages, but there can always be more.
I have a modal with a “See more” button in a component, from that button I emit an event passing the id, I take the id in the component where the table is, and I have a method where I look for the id, the values, the emit and all that works well, it emits and listens well.
This method:

Component moreInfo:

showMoreInfo() {
      store.dispatch('mapState/showMoreInfo')
      const elId = this.arrInfo.id
      this.$root.$emit('elSelected', elId)
      console.log('Event elSelected with ID:', elId)

      this.$nextTick(function() {
        store.dispatch('mapState/setExpanded', this.arrInfo)
      })
    },

Component table:

 calculateElPage(elId) {
       const foundEl = this.arr.find(item => item.id === elId)
 
       if(foundEl) {
         const index = this.arr.indexOf(foundEl)
         console.log('INDEX', index);
         const elPage = Math.floor(index / this.itemsPerPage) + 1
         console.log('ENTITYPAGE', elPage);
 
         if (elPage === this.page) {
           this.page = elPage
           console.log('PAGE', this.page);
      }
        return entityPage
      } else {
        return -1
      }
    },
mounted() {
    this.$root.$on('elSelected', (elId) => {
      const elPage = this.calculateElPage(elId)
      console.log('Element with ID', elId, 'is on the page:', elPage);
    })
}
scrollToRowExpanded(el) {
      //If the action is a display, scroll
      if (el.value) {
        //It takes a while for vuetifiy to add the row and expanded classes
        setTimeout(() => {
          const selectedRow = document.querySelector(
          '.v-data-table__expanded__content'
          ).previousElementSibling
          const tableHeader = document.querySelector('.v-data-table-header')
            .clientHeight
          const barToScroll = document.querySelector(
            '#entities__table .v-data-table__wrapper'
          )
          selectedRow.scrollIntoView()
          barToScroll.scrollBy({
            top: -tableHeader,
            behaviour: 'smooth'
          })
        }, 10)
      }
    },

This previously worked but only if the element is on page 1, so I had to implement new logic

How do you get a random value for a variable in JavaScript? [closed]

Hey so im making an ambient DVD like animation, and i have 3 circles/DVD logos for this setup, i wanna set it’s initial position to be random on a 100% width and 100vh height container (fullscreen) Here’s my current setup:

const container = document.querySelector('.background-container');
const orange = document.querySelector('.circ-o');
const lime = document.querySelector('.circ-l');
const green = document.querySelector('.circ-g');
const FPS = 30;

// Orange circle moving velocity variables
let xPositionO = 10;
let yPositionO = 10;
let xSpeedO = 5;
let ySpeedO = 5;
// Lime circle moving velocity variables
let xPositionL = 10;
let yPositionL = 10;
let xSpeedL = 5;
let ySpeedL = 5;
// Green circle moving velocity variables
let xPositionG = 10;
let yPositionG = 10;
let xSpeedG = 5;
let ySpeedG = 5;

function update(){
    orange.style.left = xPositionO + 'px';
    orange.style.top = yPositionO + 'px';
    lime.style.left = xPositionL + 'px';
    lime.style.top = yPositionL + 'px';
    green.style.left = xPositionG + 'px';
    green.style.top = yPositionG + 'px';
}

setInterval(() => {
    if(xPositionO + orange.clientWidth >= window.innerWidth || xPositionO <= 0){
        xSpeedO = -xSpeedO;
    }
    if(yPositionO + orange.clientWidth >= window.innerWidth || yPositionO <= 0){
        ySpeedO = -ySpeedO;
    }
    if(xPositionL + lime.clientWidth >= window.innerWidth || xPositionL <= 0){
        xSpeedL = -xSpeedL;
    }
    if(yPositionL + lime.clientWidth >= window.innerWidth || yPositionL <= 0){
        ySpeedL = -ySpeedL;
    }
    if(xPositionG + green.clientWidth >= window.innerWidth || xPositionG <= 0){
        xSpeedG = -xSpeedG;
    }
    if(yPositionG + green.clientWidth >= window.innerWidth || yPositionG <= 0){
        ySpeedG = -ySpeedG;
    }
    xPositionO += xSpeedO;
    yPositionO += ySpeedO;
    xPositionL += xSpeedL;
    yPositionL += ySpeedL;
    xPositionG += xSpeedG;
    yPositionG += ySpeedG;
    update();
//1000ms divided by FPS constant
}, 1000/FPS)

I set all the xPosition and yPosition of all the circle to start at 10 and i then added a ‘px’ unit in the update function which will be executed each 1000/30ms, each time the 3 circles/DVD logos hit the border of the container, it would then set its speed to a negative value, making it look as if it is bouncing from the borders

Any help on this would be greatly appreciated!

Is it possible to change variable value inside this function?

Is it possible to change the value of p inside the mf function via the call to up function passing it the p variable?

Theoretically it should be possible because javascript passes references of variables to functions, I think, by default

function up(p){
    p++;
    console.log('p from up function: ' + p);
}

function mf(){
    let p = 15;
    console.log('p from mf function: ' + p);
    return () => {
        console.log('p from arrow function before: ' + p);
        up(p);
        console.log('p from arrow function after: ' + p);
    }
}

let tf = mf()
tf()

After the call to tf() function I expected it to increase the value of p inside mf function but every time up function is receiving the same value of p that is 15

Zoom In/Out particular Object with Touch in Fabric JS

I wanted to get Zoom In/Out functionality worked for the particular Object with Touch in Fabric JS.

I found that whole canvas being zoom in/out but for specific object from multiple is not possible.

Can anyone help how to achieve?

I tried to search multiple solutions online, but could not get answer for specific object zoom with touch

Estou enfrentando problema com ajax [closed]

I’m facing a problem with the ajax request… it gets my array all right but it’s not sending it to my $_SERVER, to get another URL, is anyone having a similar problem who can help me!!! I tried everything until I narrowed it down and found the problem, I’ve tried different methods, there’s one that I even managed to do…but currently it no longer meets my needs!

Sending an image (png) from my back (Java spring) to the front (react) and printing it

We’re encountering difficulties displaying images fetched from a Java Spring backend in a React frontend. Despite successfully retrieving the image data from the backend, we’re unable to render it in the tag on the frontend.

here is what my back send:

   @PostMapping("/getProduct/{type}")
    @ResponseBody
    public ResponseEntity<byte[]> getProduct(@PathVariable("type") String productName) {
        String filePath = DIRECTORY_UPLOAD + PRODUCTS + File.separator;
        List<File> files = findAllFile(filePath);


        File productFile = files.stream()
                .filter(f -> f.getName().contains(productName))
                .findFirst()
                .orElse(null);

        if (productFile != null && productFile.exists()) {
            try {
                byte[] imageBytes = Files.readAllBytes(productFile.toPath());

                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_PNG)
                        .body(imageBytes);
            } catch (IOException e) {
                e.printStackTrace(); // Handle exception appropriately
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
            }
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

and how my front treat it :

 getImage(type: string): Promise<Response> {

    return axios.post("api" + PATH_UPLOAD +"/getProduct/" + type.replace("/",""), {
      headers: {
        ...authHeader(),
        "Content-Type": "multipart/form-data",
      },

    });
  }
 useEffect(() => {
        const fetchImage = async () => {

            await ProductsService.getImage(data.type).then(async res => {
                if (res.status === 200) {
                    const file = new Blob([res.data], {
                        type: "image/png",
                    });
                    //Build a URL from the file
                    let fileurl = URL.createObjectURL(file);
                    console.log(fileurl);
                    setProductImgURL(fileurl);

                }

            } )
        } ;
        fetchImage();
    } , []);
         {
                                    productImgURL === "" ? "" : <img src={productImgURL} alt="Image Produit" className="image"  style={{width: "25%", height: "25%"}}/>
                                }

Verified backend endpoint functionality by inspecting network requests and responses.
Implemented frontend logic to fetch image data and render it in the tag.
Ensured error handling in both frontend and backend code.
Used different way to create a blob, and tried directly printing res.data

How can I limit my data.length with invariant data sizes so I don’t ever get past the lastindex? React Native

I have two list components or card stacks. 5 Decks and several cards in each deck. I am listing the 5 decks and passing it’s content to a child component when I click on it with a (selectedItem) state. Then I’m picking that up in its child component and mapping another flatlist with the cards inside.

My problem is, when I click to an index that is beyond the limit of a smaller deck. FOr example,

Deck1 = 23 cards
Deck2 = 15 cards

When I index+1 on Deck1 to anywhere past 15, and I try to click on Deck2, it says it’s out of range (obviously lol), I’d like it to reset to index(0) when I change decks. I can’t just add more cards and make them all the same amount because I am setting a new feature later where the user can build his own deck and it can be any number of cards

Here’s my Decks Component

const Decks = () => {
  const {theme} = useContext(ThemeContext)
  let activeColors = colors[theme.mode]

  const allbelts = [yellowbelt, orangebelt, greenbelt, brownbeltthree, brownbelttwo, brownbeltone]

  const ref = useRef(null);
  const [selectedItem, setSelectedItem] = useState(null);
  const [deckIndex, setDeckIndex] = useState(0);

  const handleItemPress = (item) => {
    setSelectedItem(item);
    console.log("deckIndex:", deckIndex);
  };

  return (
    <View style={{flex:1}}>
      <View style={{flex:1, marginTop: 40}}>
        <Text style={[{color:activeColors.primary}, styles.sectionheading]}>
          Testing Card Decks
        </Text>
          <Animated.FlatList
            ref={ref}
            data={allbelts}
            horizontal
            keyExtractor={(item, index) => index.toString()}
            showsHorizontalScrollIndicator={false}
            snapToInterval={ITEM_SIZE}
            decelerationRate={0}
            bounces={false}
            scrollEventThrottle={16}
            renderItem={({item, deckIndex}) => (
              <View 
                style={{}}>
                <TouchableOpacity 
                  key={deckIndex}
                  onPress={() => {
                    handleItemPress(item)
                  }}>    
                  <Animated.View 
                    style={[{
                      backgroundColor: item.color,
                      shadowColor: item.color,
                      borderColor: activeColors.bgalt}, 
                      styles.card]}>
                      <Text 
                        numberOfLines={2} 
                        style={[{color: item.color === "#F5D143" ? activeColors.black : activeColors.white}, styles.cardtitle]}>
                        {item.rank_japanese}
                      </Text>
                      <Text 
                        numberOfLines={2} 
                        style={[{color: item.color === "#F5D143" ? activeColors.black : activeColors.white}, styles.cardtitle]}>
                        {item.rank_english}
                      </Text>
                  </Animated.View>
                </TouchableOpacity>
              </View>
            )}
          />   
        <TestingCards selectedItem={selectedItem} deckIndex={deckIndex}  />
      </View>
    </View>
  )
}

export default Decks

and here is the Cards component

const Card = ({info}) => {
  const {theme} = useContext(ThemeContext)
  let activeColors = colors[theme.mode]

  const rotate = useSharedValue(0);
  
  const frontAnimatedStyle = useAnimatedStyle(() => {
    const rotateValue = interpolate(
      rotate.value, 
      [0, 1], 
      [0, 180]
    );
    return {
      transform: [
        {rotateY: withTiming(`${rotateValue}deg`, {duration: 500})}
      ]
    }
  })

  const backAnimatedStyle = useAnimatedStyle(() => {
    const rotateValue = interpolate(
      rotate.value, 
      [0, 1], 
      [180, 360]
    );
    return {
      transform: [
        {rotateY: withTiming(`${rotateValue}deg`, {duration: 500})}
      ]
    }
  })
  return (
    <View style={[styles.cardcontainer]}>
      <View style={styles.iconcnt}>
        <Pressable 
          onPress={() => {
            rotate.value = rotate.value ? 0 : 1;  
          }} 
          style={styles.icon}>
          <Icon name="swap-horizontal" size={24} color={activeColors.textcolor} />
        </Pressable>
      </View>
      <View style={styles.cardContent}>
        <Animated.View style={[ {backgroundColor: activeColors.bgalt, position:"absolute"}, styles.card, frontAnimatedStyle]}>
          <View>
            <Text 
              style={[{color: activeColors.textcolor}, styles.cardtext]}>
              {info.q}
            </Text>
          </View>
        </Animated.View>

        <Animated.View style={[ {backgroundColor: activeColors.primary}, styles.card, backAnimatedStyle]}>
          <View>
            <Text 
              style={[{color: activeColors.textcolor}, styles.cardtext]}>
              {info.a}
            </Text>
          </View>          
        </Animated.View>
      </View>
    </View>
    
  )
}

const FlashCards = ({selectedItem, deckIndex}) => {
  const {theme} = useContext(ThemeContext)
  let activeColors = colors[theme.mode]

  const [index, setIndex] = useState(0);
  const [lastIndex, setLastIndex] = useState(null);
  const [viewPosition, setViewPosition] = useState(0.5);

  const flatlistRef = useRef(null)

  useEffect(() => {
    setLastIndex(selectedItem?.questions?.length - 1);

    // console.log("selectedItem:", selectedItem);
    console.log("lastIndex at TestingCards:", lastIndex);

    flatlistRef.current?.scrollToIndex({
      index: index, 
      animated: true,
      viewPosition,
    })
  } , [index, viewPosition, lastIndex, selectedItem])

  if (!selectedItem) {
    return null;
  }
  return (
    <View style={[styles.container]}>
      <Animated.FlatList
        data={selectedItem.questions}   
        ref={flatlistRef}
        index={deckIndex}           
        keyExtractor={(item, index) => index.toString()}
        initialScrollIndex={0}
        horizontal
        showsHorizontalScrollIndicator={false}
        snapToInterval="ITEM_SIZE"
        decelerationRate={0}
        bounces={false}
        scrollEventThrottle={16}
        initialNumToRender={10} 
        onScrollToIndexFailed={index => {
            setIndex(0) 
          const wait = new Promise(resolve => setTimeout(resolve, 0));
          wait.then(() => {
            flatlistRef.current?.scrollToIndex({ index: index, animated: true });
          });
        }}
        renderItem={({item, index}) => <Card info={item} index={index} totalLength={lastIndex} seefront={true} />}
      />
      <View style={styles.btnGroup}>
        <TouchableOpacity 
          onPress={()=>{
            setIndex(0);
            setViewPosition(0.5);
          }}>
          <LinearGradient
            colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']}
            start={{ x: 0, y: 1 }}
            end={{ x: 1, y: 1 }}
            style={styles.btnPrimary}>
            <Icon name="chevron-double-left" size={24} color={activeColors.white} />
          </LinearGradient>
        </TouchableOpacity>      
        <TouchableOpacity 
          onPress={()=>{
            if (index === 0) {
              return;
            }
            setIndex(index - 1);
            setViewPosition(0.5);
          }}>
          <LinearGradient
            colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']}
            start={{ x: 0, y: 1 }}
            end={{ x: 1, y: 1 }}
            style={styles.btnPrimary}>
            <Icon name="chevron-left" size={24} color={activeColors.white} />
          </LinearGradient>
        </TouchableOpacity>               
        <TouchableOpacity 
          onPress={()=>{
            if (index === lastIndex) {
              return;
            }
            setIndex(index + 1);
            setViewPosition(0.5);
          }}>
          <LinearGradient
            colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']}
            start={{ x: 0, y: 1 }}
            end={{ x: 1, y: 1 }}
            style={styles.btnPrimary}>
            <Icon name="chevron-right" size={24} color={activeColors.white} />
          </LinearGradient>
        </TouchableOpacity>   
        <TouchableOpacity 
          onPress={()=>{

            if (index === lastIndex) {
              return;
            }
            setIndex(lastIndex - 1);
            setViewPosition(0.5); 
          }}>
          <LinearGradient
            colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']}
            start={{ x: 0, y: 1 }}
            end={{ x: 1, y: 1 }}
            style={styles.btnPrimary}>
            <Icon name="chevron-double-right" size={24} color={activeColors.white} />
          </LinearGradient>
        </TouchableOpacity>            
      </View>
    </View>
  )
}

export default FlashCards

Stop Gigya log in from directing back to the log in page

We are using Gigya as our log in service on our SAP Commerce site.

This is the code that is executed when a user clicks the log in button:

ssoLogin(language: string): void {
gigya.sso.login({
authFlow: “redirect”,
context: {
appName: “eCom”,
lang: language
},
useChildContext: true
});
}

We have noticed that when the user logs in they are first directed back to the log in page and then to the actual store they are logging in to.

How can we make it so that they’re not directed to the log in page but are directed straight to the store?

We have tried changing authFlow from “redirect” to “popup” and we have also tried passing a redirect url in the method call, but neither option stopped gigya from directing the user to the log in page after logging in.

Icone of font awesome dont change

I want to change the class ‘fa-meh-blank’ to ‘fa-smile-wink’ but it doesn’t work.

When I flip the two classes, however, it works. I don’t understand what’s wrong, what would anyone have an idea?

const icone = document.querySelector("i");
console.log(icone);

//Je soumets

icone.addEventListener('click', function() {
  console.log('icône cliqué');
  icone.classList.toggle('happy');
  icone.classList.toggle('fa-smile-wink');
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container">
  <div class="bloc-central">
    <h1>Projet Abonnez-vous</h1>
    <iframe width="560" height="315" src="https://www.youtube.com/embed/ggGT2N4l_08?si=hFk7Xzw16cEEzi6x" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
      referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
    <div class="bloc-btn">
      <i class="far fa-meh-blank"></i>
      <button class="btn">Abonnez-vous</button>
    </div>
  </div>
</div>

How can I insert existing SVG graphics with tag and javascript?

I am unable to display a SVG graphic built via JavaScript.
The svg is stored in the part. I am first correctlty displaying svg using html. If I try to display same graphic with JavaScript, nothing is displayed.
Here is my full code:

<!DOCTYPE html>
<html>
<head>
  <title> Testing SVG insertion</title>
  <style>
    svg.defs-only {
      display: block;
      position: absolute;
      height: 0;
      width: 0;
      margin: 0;
      padding: 0;
      border: none;
      overflow: hidden;
    }
  </style>
  <svg class="defs-only">
    <symbol id="shape" width="200" height="200" viewbox="0 0 200 200">
      <circle cx="100" cy="100" r="100" fill="currentColor" />
    </symbol>
  </svg>
</head>
<body style='background-color: lightGray;'>
  <h1> Testing SVG inclusion -- this works fine</h1>
  <svg style='width: 200px; height: 200px;'>
    <use xlink:href="#shape"></use>
  </svg>
  <h1> Testing SVG via javascript -- does not display anything </h1>
  <div id='container'></div>
  <script>
    let div = document.getElementById ('container');
    let svg  = document.createElement ('svg');
    svg.style.height = '200px';
    svg.style.width = '200px';
    let use  = document.createElement ('use');
    use.setAttribute("xlink:href", "#shape");
    svg.appendChild (use);
    div.appendChild (svg);
  </script>
</body>
</html>```

“My weather site should show images based on weather. How to fix?” [closed]

enter code here

enter code here

enter code here

enter code here

I’m developing a weather website. How can I make it display images based enter image description hereon the weather data? For example, if it’s sunny, I want it to show a sunny weather image. Currently, it doesn’t display the images correctly. How can I fix this?”

“I attempted to integrate image display based on weather data into my weather website, expecting it to show relevant images such as sunny weather pictures. However, the expected images aren’t being displayed as intended. What could be the issue?”

Node Redis-OM: this[#schema].generateId is not a function

Hi everyone I am trying to save an entinty into a redis repository, the driver is correctly connected the schema is created as edxpected same with the repo. The problem comes when I try to save the entity, The exception I am getting is: TypeError: this[#schema].generateId is not a function at Repository.save.

I already tried with other schema types of old redis-om version usind Class Session extends Entity {} but I get the same error every time.

the versión of redis-node-om is 0.4.3.

Here I provide the code that isn’t working:

Middleware.js

const sessionRepository = getSessionRepo(redisClient);
const session = createSessionObj(req);
console.log("[REDIS] **GUARDANDO DATOS EN EL REPOSITORIO DE REDIS**");
const storedSession = await sessionRepository.save(session);

sessionSchema

const sessionSchema = new Schema(
    "session",
    {
        userId: { type: "string", field: "user_id" },
        role: { type: "string", field: "user_role" },
        jwt: { type: "string", sortable: "yes", field: "user_jwt", weight: 1 },
    },
    { dataStructure: "HASH" }
);

getSessionRepo function

function getSessionRepo(redisClient) {
    console.log(sessionSchema);
    const sessionRepository = new Repository(sessionSchema, redisClient);
    console.log(sessionRepository);
    return sessionRepository;
}

createSession function:

function createSessionObj(req) {
    let session = {};
    session.userId = req.body.userId;
    session.role = req.body.role;
    session.jwt = req.body.tokenJWT;

    return session;
}

Auto Pagination issues in Django, how to fix?

Auto Pagination issues in Django, how to fix?

How to resolve duplication with automatic pagination?
There’s a template home.html and home_list.html;

In home_list.html, JSON format is successfully passed, but Ajax misbehaves and creates a bunch of duplicate posts during automatic pagination; how to fix?

home.html:

<script>
    $(document).ready(function(){
        var nextPageUrl = '/load-posts/';  // Using URL for loading posts
        
        function loadMorePosts() {
            // Display loading element
            //$('#loading').text('Loading...');
    
            // Perform a GET request to the server
            $.get(nextPageUrl, function(data) {
                // Hide loading element
                //$('#loading').text('Load more');
    
                // Append HTML with posts to the end of the container
                $('#post_contenter').append(data.posts_html);
    
                // Update URL for the next page
                nextPageUrl = data.next_page_url;
            }).fail(function() {
                // Handle request error if it occurs
                console.error('Error loading posts');
                // Hide loading element
                $('#loading').hide();
            });
        }
    
        // Event handler for page scroll
        $(window).scroll(function() {
            if($(window).scrollTop() + $(window).height() >= $(document).height()) {
                // Call the function to load additional posts
                loadMorePosts();
            }
        });
    
        // Initialize loading of the first page of posts when the page is loaded
        loadMorePosts();
    });
</script>

views.py:

from django.shortcuts import render, redirect
from usercreatepost.forms import PostForm
from publication.models import Userpublication
from user.models import Profile****, Subscription
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.urls import reverse
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.db.models import Q

@login_required
def create_post(request):
    form = PostForm(request.POST or None)

    # If request is POST, save the form
    if request.method == 'POST':
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('home')

    # Get IDs of users subscribed by the current user
    subscribed_user_ids = Subscription.objects.filter(subscriber=request.user).values_list('target_user', flat=True)

    # Get all posts from authors subscribed by the current user
    subscribed_posts = Userpublication.objects.filter(author__in=subscribed_user_ids)

    # Get all posts from the current user
    own_posts = Userpublication.objects.filter(author=request.user)

    # Merge post lists
    all_posts = (subscribed_posts | own_posts).order_by('-time_create')

    # Get the page posts object for display
    page_posts = all_posts

    context = {'form': form, 'post_lists': page_posts, 'title': '**** | News'}
    return render(request, '****/home.html', context)


def load_posts(request):
    # Get page number from the request
    page_number = request.GET.get('page', 1)  # Set default value to 1

    # Get IDs of users subscribed by the current user
    subscribed_user_ids = Subscription.objects.filter(subscriber=request.user).values_list('target_user', flat=True)

    # Get all posts subscribed by the current user or authored by them
    all_posts = Userpublication.objects.filter(Q(author__in=subscribed_user_ids) | Q(author=request.user))

    # Create Paginator object
    paginator = Paginator(all_posts, 10)  # 10 posts per page

    try:
        # Get objects for the current page
        current_page_posts = paginator.page(page_number)
    except PageNotAnInteger:
        # If page number is not an integer, show first page
        current_page_posts = paginator.page(1)
    except EmptyPage:
        # If page number is out of range, return empty response
        return JsonResponse({'posts_html': '', 'next_page_url': None})

    # Render HTML with posts for the current page
    posts_html = render_to_string('****/home_list.html', {'posts': current_page_posts})

    # Get URL for the next page if it exists
    next_page_url = None
    if current_page_posts.has_next():
        next_page_url = f"{reverse('load_posts')}?page={current_page_posts.next_page_number()}"

    # Return JSON response with HTML and URL for the next page
    return JsonResponse({'posts_html': posts_html, 'next_page_url': next_page_url})

Why are svelte derived stores always recreated on get()?

Now this is more directed towards Svelte authors I suppose, but I just recently fully realized that derived stores are constantly recreated on get.

Example

I thought they’d only be recreated when the inputs would change — not every time a get is called. Especially weird is that if the derived stores are linked, the whole tree is traversed.

I do get that the derived stores should always return the exact same value for the same input but if someone, with no time to think too deeply about it, would depend on the derived store to only be recomputed on the original store change it would cause rather strange bugs.