Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidallenlewis/78dcf949bbdb01e0a11783af9c5e87ef to your computer and use it in GitHub Desktop.
Save davidallenlewis/78dcf949bbdb01e0a11783af9c5e87ef to your computer and use it in GitHub Desktop.
for-david-c.js
/*
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