The error you're encountering, "Uncaught ReferenceError: $wire is not defined," typically occurs when the $wire object is not available in the scope where you're trying to use it. This can happen if the JavaScript is executed before Livewire has fully initialized or if the $wire object is not properly referenced.
Here are a few steps to resolve this issue:
-
Ensure Livewire is Loaded: Make sure that Livewire's JavaScript is properly included and loaded on your page. This is usually done by including
@livewireScriptsin your Blade template, typically just before the closing</body>tag. -
Use Livewire Hooks: If you're using Alpine.js, you can leverage Livewire hooks to ensure that your JavaScript runs after Livewire has initialized. For example, you can use the
livewire:loadevent to ensure that$wireis available:<script> document.addEventListener('livewire:load', function () { function updateInput() { let inputValue = Array.from(inputs).reduce(function (otp, input) { otp += input.value.length ? input.value : " "; return otp; }, ""); if (inputValue.trim().length >= 2) { $wire.dispatch('post-created', { refreshPosts: true }); } } // Ensure your function is called in the right context // For example, attach it to an event listener document.querySelectorAll('input').forEach(input => { input.addEventListener('input', updateInput); }); }); </script> -
Check the Context: Ensure that the function
updateInputis being called in a context where$wireis available. If you're using this function in a component, make sure it's within the scope of that component. -
Use Livewire Component Reference: If you're working within a specific Livewire component, you might need to reference
$wirethrough the component's context. For example, if you're using Alpine.js, you can do something like this:<div x-data x-init="$watch('inputValue', value => { if (value.trim().length >= 2) { $wire.dispatch('post-created', { refreshPosts: true }); } })"> <input x-model="inputValue" type="text"> </div> -
Check for Conflicts: Ensure there are no JavaScript errors or conflicts that might prevent Livewire from initializing properly. Check your browser's console for any other errors that might be related.
By following these steps, you should be able to resolve the issue with $wire not being defined. If the problem persists, double-check that your Livewire and Alpine.js versions are compatible and that there are no other JavaScript errors on the page.