Update JS arrays live

How do i update a Javascript Array live? Like, if someone adds a new thing to the array while i am on the website, how do i make the array update without having to reload the page?

Where is the array going to be changed from? If you’re changing it from within the project editor the only way to do it would be to have it in a seperate json file and then repeatedly use the fetch api to fetch the data, but that could cause your project to end up having too many requests. If the user’s changing it through dev tools or through an input element or something like that, you should look into a framework that supports reactivity, like vue. If you’re setting it in a database server side, or something similar, you should look into websockets.

2 Likes

The basic concept is to listen for changes to variables. See this thread that uses getters and setters to listen for variable value changes and calls a function accordingly:

But you might wanna use a framework like Vue or React (as @Pufferfish101007 rightfully suggested) as it makes it a whole lot easier. These frameworks listen for updates and automatically updates the values wherever it is being used.

Extra article that you might find useful about “Vue’s Reactivity” (taken from the VueJS documentation): Reactivity in Depth — Vue.js

4 Likes