react component this.value is null even when it's populated - javascript

Here a simplified version of a React component I have:
class Example extends Component {
constructor(props) {
super(props);
this.state = {key : 10 };
this.value = null;
}
componentDidMount() {
this.fetchValueFromServer();
this.fetchSecondValueFromServer();
}
fetchValueFromServer() {
fetch_value_from_server(this.state.key).then( (value) => {
this.value = value;
});
}
fetchSecondValueFromServer() {
is_ready(this.value).then(() => {
console.log("there");
});
}
}
I expect to see the console.log("there") printed but this.value always remains null, even thou is set in the fetchValueFromServer. Why is this?
if you are curious to how is_ready looks it's a simple promise:
function is_ready(variable) {
return new Promise((resolve, reject) => {
let interval = setInterval(() =>
{
if (variable) {
clearInterval(interval);
resolve();
}
}, 100);
});
}

The problem is with the logic of the is_ready function. It looks like you want that function to repeatedly check if that value is there, then resolve when it is. However, because of how closures in JS work, that variable argument will only ever have one value in the context of that function's body, even after this.value changes. Look at this small example:
let secret = 'not found yet'
function checkSecret(secretArg) {
setInterval(() => {
console.log(secretArg)
}, 500)
}
checkSecret(secret)
setTimeout(() => { secret = 'secret found!' }, 1000)
This code will always print 'not found yet', because it's checking the secretArg variable that's been assigned locally, and not the secret variable directly.

Looks like you need to resolve with the variable value within the function is_ready, like so:
resolve(variable);
Then add a param to your console log to determine more, like so:
fetchSecondValueFromServer() {
is_ready(this.value).then((returnValue) => {
console.log("there", returnValue);
});
}

figured it, the value in is_ready is passed by value! Javascript needs to implement & so we can pass crap by ref!

Related

Javascript method to be able see if a value changes without re rendering the page

I am trying to be able to read a value that is boolean to see if a user did a specific action or not and I am using the ReactJS functional component style. I am trying to read the runValue in my code to see if the run() method changed the value and I want to be able to read this value without recalling the function.
I want to be able to put in my useEffect method this line of code;
Run.RunFunction().run((index) => {
if (index) {
\\\ do stuff here if index is true
} else {
///if index is false
}
}
my code
const Run = {
RunFunction: () => {
let runValue = false;
return {
run() {
runValue = true
},
listener: function(val) {},
checkStatus: function(listen) {
this.listener = listen
}
}
},
}
Run.RunFunction().checkStatus((index) => {
if (index) {
console.log('running')
} else {
console.log('not running')
}
});
I am having trouble having this code to work and I want to be able to see the value of the runValue initially and if it changes.
Thank you

Global loaded data in VueJs is occasionally null

I'm new to VueJs and currently trying to load some data only once and make it globally available to all vue components. What would be the best way to achieve this?
I'm a little bit stuck because the global variables occasionally seem to become null and I can't figure out why.
In my main.js I make three global Vue instance variables:
let globalData = new Vue({
data: {
$serviceDiscoveryUrl: 'http://localhost:40000/api/v1',
$serviceCollection: null,
$clientConfiguration: null
}
});
Vue.mixin({
computed: {
$serviceDiscoveryUrl: {
get: function () { return globalData.$data.$serviceDiscoveryUrl },
set: function (newUrl) { globalData.$data.$serviceDiscoveryUrl = newUrl; }
},
$serviceCollection: {
get: function () { return globalData.$data.$serviceCollection },
set: function (newCollection) { globalData.$data.$serviceCollection = newCollection; }
},
$clientConfiguration: {
get: function () { return globalData.$data.$clientConfiguration },
set: function (newConfiguration) { globalData.$data.$clientConfiguration = newConfiguration; }
}
}
})
and in my App.vue component I load all the data:
<script>
export default {
name: 'app',
data: function () {
return {
isLoading: true,
isError: false
};
},
methods: {
loadAllData: function () {
this.$axios.get(this.$serviceDiscoveryUrl)
.then(
response => {
this.$serviceCollection = response.data;
let configurationService = this.$serviceCollection.services.find(obj => obj.key == "ProcessConfigurationService");
this.$axios.get(configurationService.address + "/api/v1/clientConfiguration").then(
response2 => {
this.$clientConfiguration = response2.data;
}
);
this.isLoading = false;
})
}
},
created: function m() {
this.loadAllData();
}
}
</script>
But when I try to access the $clientConfiguration it seems to be null from time to time and I can't figure out why. For example when I try to build the navigation sidebar:
beforeMount: function () {
let $ = JQuery;
let clients = [];
if (this.$clientConfiguration === null)
console.error("client config is <null>");
$.each(this.$clientConfiguration, function (key, clientValue) {
let processes = [];
$.each(clientValue.processConfigurations, function (k, processValue) {
processes.push(
{
name: processValue.name,
url: '/process/' + processValue.id,
icon: 'fal fa-project-diagram'
});
});
clients.push(
{
name: clientValue.name,
url: '/client/' + clientValue.id,
icon: 'fal fa-building',
children: processes
});
});
this.nav.find(obj => obj.name == 'Processes').children = clients;
The most likely cause is that the null is just the initial value. Loading the data is asynchronous so you'll need to wait for loading to finish before trying to create any components that rely on that data.
You have an isLoading flag, which I would guess is your attempt to wait for loading to complete before showing any components (maybe via a suitable v-if). However, it currently only waits for the first request and not the second. So this:
this.$axios.get(configurationService.address + "/api/v1/clientConfiguration").then(
response2 => {
this.$clientConfiguration = response2.data;
}
);
this.isLoading = false;
would need to be:
this.$axios.get(configurationService.address + "/api/v1/clientConfiguration").then(
response2 => {
this.$clientConfiguration = response2.data;
this.isLoading = false;
}
);
If it isn't that initial value that's the problem then you need to figure out what is setting it to null. That should be prety easy, just put a debugger statement in your setter:
$clientConfiguration: {
get: function () { return globalData.$data.$clientConfiguration },
set: function (newConfiguration) {
if (!newConfiguration) {
debugger;
}
globalData.$data.$clientConfiguration = newConfiguration;
}
}
Beyond the problem with the null, if you're using Vue 2.6+ I would suggest taking a look at Vue.observable, which is a simpler way of creating a reactive object than creating a new Vue instance.
Personally I would probably implement all of this by putting a reactive object on Vue.prototype rather than using a global mixin. That assumes that you even need the object to be reactive, if you don't then this is all somewhat more complicated than it needs to be.

Reload HTML elements with javascript not working

I get a list of items and use it to dynamically create an HTML list
_loadList(){
HttpUtils.get('http://myserver/list/users/')
.then((res) => {
const self = this;
res.forEach((item) => {
userListContainer.append('<li> item.name </li>')
});
});
}
I call this function in the constructor, everything is working fine
constructor() {
this._loadList();
}
I am trying to recall this function every 5 seconds to update the list with the new result:
constructor() {
const that = this;
this._loadList();
window.setInterval(function(){
that._loadList();
}, 5000);
}
The function is called, the received result contains the new content, but the HTML is not updated. Do you have an idea about the problem?
You can try below code that will work for in your case. You can checkout https://es6console.com/jgyxgm1f/ example which will alert random number (in your case it's equivalent of adding new data coming from API response).
_loadList = () => {
HttpUtils.get('http://myserver/list/users/')
.then((res) => {
userListContainer.empty();
res.forEach((item) => {
userListContainer.append('<li> item.name </li>')
});
});
}
constructor = () => {
this._loadList();
window.setInterval(() => {
this._loadList();
}, 5000);
}

VueJS how to use _.debounce on data changes

I'm building a little vue.js-application where I do some post requests. I use the watch-method to whach for api changes which then updates the component if the post request is successfull. Since the watcher constantly checks the API I want to add the ._debounce method but for some reason it doesn't work.
here is the code:
<script>
import _ from 'lodash'
export default {
data () {
return {
cds: [],
cdCount: ''
}
},
watch: {
cds() {
this.fetchAll()
}
},
methods: {
fetchAll: _.debounce(() => {
this.$http.get('/api/cds')
.then(response => {
this.cds = response.body
this.cdCount = response.body.length
})
})
},
created() {
this.fetchAll();
}
}
</script>
this gives me the error: Cannot read property 'get' of undefined
Can someone maybe tell me what I'm doing wrong?
EDIT
I removed the watch-method and tried to add
updated(): {
this.fetchAll()
}
with the result that the request runs in a loop :-/ When I remove the updated-lifecycle, the component does (of course) not react to api/array changes... I'm pretty clueless
Mind the this: () => { in methods make the this reference window and not the Vue instance.
Declare using a regular function:
methods: {
fetchAll: _.debounce(function () {
this.$http.get('/api/cds/add').then(response => {
this.cds = response.body
this.cdCount = response.body.length
})
})
},
Other problems
You have a cyclic dependency.
The fetchAll method is mutating the cds property (line this.cds = response.body) and the cds() watch is calling this.fetchAll(). As you can see, this leads to an infinite loop.
Solution: Stop the cycle by removing the fetchAll call from the watcher:
watch: {
cds() {
// this.fetchAll() // remove this
}
},

Autosave to database after timeout

I want to perform autosave when a user fills out a form in a React component. The ajax call should be triggered when 3 seconds has passed since last onChange event.
My code below is inspired from an instructive article which shows how to accomplish this with setTimeout and clearTimeout. But I'm doing something wrong in my React implementation - the 3 sec delay isn't respected when typing.
Any ideas what's wrong here? Or is my thinking all together wrong about how to solve this?
class Form extends Component {
constructor() {
super();
this.state = {
isSaved: false
};
this.handleUserInput = this.handleUserInput.bind(this);
this.saveToDatabase = this.saveToDatabase.bind(this);
}
saveToDatabase() {
var timeoutId;
this.setState({isSaved: false});
if (timeoutId) {
clearTimeout(timeoutId)
};
timeoutId = setTimeout( () => {
// Make ajax call to save data.
this.setState({isSaved: true});
}, 3000);
}
handleUserInput(e) {
const name = e.target.name;
const value = e.target.value;
this.setState({[name]: value});
this.saveToDatabase();
}
render() {
return (
<div>
{this.state.isSaved ? 'Saved' : 'Not saved'}
// My form.
</div>
)
}
Inside saveToDatabase method you are defining a new and undefined timeoutId variable every time the method is called. That's why the if statement never gets called.
Instead, you need to scope out the variable and create a class data property in the constructor.
constructor() {
super();
this.state = {
isSaved: false
};
this.timeoutId = null;
this.handleUserInput = this.handleUserInput.bind(this);
this.saveToDatabase = this.saveToDatabase.bind(this);
}
saveToDatabase() {
this.setState({isSaved: false});
if (this.timeoutId) {
clearTimeout(this.timeoutId)
};
this.timeoutId = setTimeout( () => {
// Make ajax call to save data.
this.setState({isSaved: true});
}, 3000);
}

Categories