I'm working with a Alpine.data global and I'm looking to concatenate arrays when my loadJobs method fires. I'm not familiar to proxies in JS and I don't really understand why my data property returns a Proxy object instead of a simple array.
Here's the piece of code I'm working with :
jobState = {
low: 5,
high: 10,
isLoaded: false
}
document.addEventListener("alpine:init", () => {
Alpine.data("loadMoreJobs", () => ({
data: [],
loadJobs() {
// Update jobState
jobState.low = jobState.high
jobState.high += 5
const requestParams = {
dataType: 'json',
method: 'GET'
}
fetch(`http://127.0.0.1:3000/jobs/list/${jobState.low}/${jobState.high}`, requestParams)
.then((data) => {
return data.json()
})
.then((data) => {
this.data = [...this.data, data]
})
}
}))
})
data logs out as Proxy because that's how Alpine.js' reactivity works: it wraps all relevant objects in Proxy in order to hook into changes into said objects.
The Proxies should work the same as the underlying data structures, the only difference is Alpine can hook into operations on the proxy (re-assignment, mutation etc.).
As mentioned in the comments thread. One way to unwrap the Proxy and get a copy of the original data structure is to use JSON.parse(JSON.stringify(data)) (or another deep-cloning approach eg. structuredClone which isn't widely available yet).