Return to a filtered page

I am using Wix Studio for a new website. On my portfolio page, I have a gallery repeater that shows all of the projects which can be filtered by category via dropdown menu. I want it so that when visitors click on an item and views the single dynamic page, that they can return to the portfolio page with the previously selected category selected to filter the content. I was able to write the code to get it to remember the last category selected and to have it in the dropdown menu text when returning but it will not filter the content automatically. I need it to act as if the category was clicked from the dropdown menu unless there is a better way. Here is the code that I used: import { session } from ‘wix-storage’;

$w.onReady(function () {
// Step 1: Store the selected filter state
$w(“#categoryDropdown”).onChange(() => {
let selectedCategory = $w(“#categoryDropdown”).value;
session.setItem(“selectedCategory”, selectedCategory);
});

// Step 2: Retrieve the filter state on the Work page
let selectedCategory = session.getItem("selectedCategory");
if (selectedCategory) {
    $w("#categoryDropdown").value = selectedCategory;
    filterProjects(selectedCategory); // Function to filter projects
}

});

function filterProjects(category) {
// Your logic to filter projects based on the category
}

// Set the dropdown value to the desired category
$w("#categoryDropdown").value = dropdownValue;

// Store the selected category in session storage
session.setItem("selectedCategory", desiredCategory);

// Filter projects based on the desired category
filterProjects(desiredCategory);

});

It seems to be related to the timing of when the filterProjects function is called. In your code, you’re calling filterProjects inside the $w.onReady function. However, the onReady function is only called once when the page is loaded. If the page is already loaded when the category is selected, the filterProjects function won’t be called again, and the projects won’t be filtered.

To fix, you should call the filterProjects function inside the onChange event handler of the dropdown menu. This way, the function will be called every time the selected category changes, not just when the page is loaded.

import { session } from 'wix-storage';

$w.onReady(function () {
    // Step 1: Store the selected filter state
    $w("#categoryDropdown").onChange(() => {
        let selectedCategory = $w("#categoryDropdown").value;
        session.setItem("selectedCategory", selectedCategory);
        filterProjects(selectedCategory); // Call the filter function here
    });

    // Step 2: Retrieve the filter state on the Work page
    let selectedCategory = session.getItem("selectedCategory");
    if (selectedCategory) {
        $w("#categoryDropdown").value = selectedCategory;
        filterProjects(selectedCategory); // Function to filter projects
    }
});

function filterProjects(category) {
    // Your logic to filter projects based on the category
}