property changed on event does not maintain its new value #3402
-
I want to send a file to an API and retrieve its response and show it in the browser, here's how I did it, in a minimal representation: <html>
<head>
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<!-- <script defer src="index.js"></script> -->
</head>
<body>
<div x-data="uploader()">
<form>
<input type="file" x-on:change="file = $event.target.files[0]" />
<button x-show="file" x-on:click="upload()">Upload</button>
</form>
<span x-text="message"></span>
</div>
</body>
<script>
function uploader() {
return {
file: null,
message: "",
upload() {
// sending file as FormData to an API...
console.log(this.file);
this.message = "File sent!";
},
};
}
</script>
</html> The problem is the span tag doesn't update to "File sent!" after uploading the file. It actually flickers with the new value and then goes back to being empty. How can I make the "message" property be updated every time I submit a file? In another similar issue, if I put the "uploader()" function in another file and load it with defer inside the head tag, the browser says it couldnt find the "uploader" property. Why is that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
the issue is that the form is submitting, which is causing a reload. You can make your I'd advise to use
Because your code defining it ran AFTER alpine ran to try to find it. |
Beta Was this translation helpful? Give feedback.
the issue is that the form is submitting, which is causing a reload. You can make your
button
havetype="button"
on it to avoid this (recommended) or add@submit.prevent
on theform
element itself (less recommended). Could even remove theform
element entirely since it has a lot of behaviors attached to it that you're deliberately avoiding.I'd advise to use
Alpine.data
to set up your data components, instead of using global functions.Because your code defining it ran AFTER alpine ran to try to find it.