I am trying out iAPI with help of ChatGPT AI and Claude AI but stuck with getContext() function. As soon as I use getContext() in action, it will fail.
debug.js?ver=619affca133d04fbead9:81
Uncaught Error: Cannot call
getContext()when there is no scope. If you are using an async function, please consider using a generator instead. If you are using some sort of async callbacks, likesetTimeout, please wrap the callback withwithScope(callback).
I am trying generator function, but I will fail anyway.
withScope( actions.performSearch() ); I am adding withScope() but that also does not help.
I want to use getContext() in async mode.
Is there a clear example for this?
/** * WordPress Interactivity API store for Interactive Post Search */ import { store, getContext, withScope } from '@wordpress/interactivity'; let debounceTimer; store('interactive-post-search', { actions: { updateSearchTerm: (event) => { const context = getContext(); context.searchTerm = event.target.value; // Get the root element once, while event is fresh const rootEl = event.target.closest('[data-wp-interactive]'); // Auto-search with debounce when user types clearTimeout(debounceTimer); const { actions } = store('interactive-post-search'); if (context.searchTerm.length >= 3) { debounceTimer = setTimeout(() => { const { actions } = store('interactive-post-search'); withScope( actions.performSearch() ); }, 500); } else if (context.searchTerm.length === 0) { // Clear results when input is cleared context.results = []; context.hasSearched = false; context.totalFound = 0; } }, performSearch: () => { const context = getContext(); console.log(context); } } });