79269480

Date: 2024-12-10 19:16:45
Score: 0.5
Natty:
Report link

I have a very similar instance here, and it happens on some of my pages, not all, so it's confusing as to how to address it. I have an search bar where I want to fetch results from the back end and display them in a pop-up div under the search bar. If I use document.addEventListener('alpine:init'... it just doesn't work, whereas if I place the object directly into the x-data property in html (and avoiding use of appState), it works fine. I'm confused because using the appState approach that is initialized in javascript works fine on several of my other pages. Is there a known issue with Alpine being inconsistent in its initiazation or scope access?

I also ended up just leaving it inside the x-data, even those this feels verbose and messy (and you lose the formatting on the js code).

  <!-- SEARCH BAR AND RESULTS -->
  <div x-data="appState" class="relative mx-auto flex-1 px-4">

    <!-- Search Input -->
    <input type="text" x-model="queryString" @keydown.enter="handleSearch"
      class="w-full border border-gray-300 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-green-400"
      placeholder="Type your query and press Enter" />

    <!-- Results Box -->
    <div x-show="searchResult" class="absolute bg-white border border-gray-200 rounded-lg shadow-lg w-full mt-2 p-3"
      @click.outside="searchResult = null" x-transition>
      <p class="text-gray-800 font-medium">Results:</p>
      <p x-text="searchResult" class="text-green-600 font-mono"></p>
    </div>
  </div>

And in JS:

document.addEventListener('alpine:init', () => {

    Alpine.data('appState', () => ({
    queryString: '',
    searchResult: null,
    async handleSearch() {
      // Validate the query string
      if (this.queryString.trim() === '') {
        console.error('Query is empty.');
        return;
      }

      try {
        // Make the POST request
        const response = await fetch('/api/get-results', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ query: this.queryString }), // Send the query as expected by the server
        });

        // Check for HTTP errors
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // Parse the JSON response
        const data = await response.json();

        // Use the `queryString` property from the response
        if (data && data.responseString) {
          this.searchResult = data.responseString;
        } else {
          console.error('Unexpected response format:', data);
          this.searchResult = null;
        }
      } catch (error) {
        console.error('Error fetching search results:', error);
        this.searchResult = null;
      }
    }
  }))
})
Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Jon Haider