Last active
May 2, 2025 14:46
-
-
Save davidallenlewis/78dcf949bbdb01e0a11783af9c5e87ef to your computer and use it in GitHub Desktop.
for-david-c.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
state.selectedFilters could be empty | |
state.selectedFilters could NOT be empty and | |
- Clicked taxonomy (queryVar) is already an object in the state.selectedFilters array | |
Look for the clicked term in the matched object | |
If the term is in there remove it, otherwise add it | |
- Clicked taxonomy is NOT already in the state.selectedFilters array | |
Create a new object to add to state.selectedFilters i.e. { queryVar, selectedTerms: [blah, blah] } | |
- Update state.selectedFilters without duplicating existing taxonomies | |
*/ | |
const updateCheckboxState = async( queryVar, termSlug ) => { | |
if ( ! queryVar ) return; | |
const { selectedFilters } = state; | |
let termSlugs; | |
// State has no terms in any taxonomy | |
if( selectedFilters.length === 0 ) { | |
console.log( 'hello if' ); | |
termSlugs = [ termSlug ]; // add new | |
// State has terms at least one taxonomy | |
} else { | |
console.log( 'hello else' ); | |
// Look for the selected taxonomy in state | |
const foundFilter = state?.selectedFilters.find( obj => obj.queryVar === queryVar ); | |
// Taxonomy is in state | |
if( foundFilter ) { | |
const existingTerms = foundFilter?.selectedTerms.split(',') ; | |
console.log( 'existingTerms A', existingTerms ); | |
termSlugs = existingTerms.includes( termSlug ) | |
? existingTerms.filter( slug => slug !== termSlug ) // remove existing | |
: [ ...existingTerms, termSlug, 'ELSE MF' ]; // add new | |
console.log( 'existingTerms B', existingTerms ); | |
console.log( 'termSlugs A', termSlugs ); | |
//update state | |
// Taxonomy is not in state | |
} else { | |
termSlugs = [ termSlug ]; // add new | |
//update state | |
} | |
} | |
console.log( 'termSlugs B', termSlugs ); | |
//update state | |
const newFilter = { queryVar, selectedTerms: termSlugs.join(',') }; | |
console.log( 'newFilter', newFilter ); | |
state.selectedFilters.push( newFilter ); // or spread for immutable | |
console.log( 'state.selectedFilters', state.selectedFilters ); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment