Access react's function with parameters from external JavaScript - reactjs

Is it possible to add onclick event inside the messages' parameter of UIKIT.notification?
Something like this:
notif__undoDelete = (param) => {
setTimeout(function(param) {
UIkit.notification(
`<div class="uk-flex uk-flex-middle uk-margin-medium-right">
<span>Exercise Deleted.</span><a onclick="{here}" class="uk-button uk-button-primary uk-button-small uk-margin-auto-left">Undo</a>
</div>`,
{ timeout: 6000, pos: "bottom-left" }
)
}, 800, param)
}

I use this answer to solve my problem
Call react component's function from external JavaScript function
I added in componentDidMount method first:
componentDidMount () {
var me = this
window.undoDelete = () => {
var external_me = this
let param = JSON.parse(external_me.event.target.getAttribute("data-param"))
me.undoDelete(param)
}
}
I have an undoDelete() method somewhere and when I call my UIkit.notification it's gonna be something like this and my react's undoDelete() method will be called. I added data-param as well to pass parameters.
UIkit.notification(
`<div className="uk-flex uk-flex-middle uk-margin-medium-right">
<span>Item Deleted.</span>
<a onclick="window.undoDeleteExternal()" data-param='`+ JSON.stringify(param) +`' className="uk-button uk-button-primary uk-button-small uk-margin-auto-left">Undo</a>
</div>`,
{ timeout: 6000, pos: 'bottom-left' }
)

Related

make vuejs component wait for the variable to become available

I have an VueJS component that list the contents of the array to the page. runner.availableResources.cores and runner.availableResources.memory come from bus creates usingbusmq npm package. They take awhile to become available, about 15s depending on IO buffer and thus not immediately available when the page renders.
The error is: [Vue warn]: Error in render: "TypeError: Cannot read property 'cores' of undefined"
How can I make Vue keep checking for values to become available?
<template>
<b-col>
<b-table striped hover :items="formatRunners"></b-table>
</b-col>
</template>
<script>
const fileSize = require("filesize");
export default {
name: "RunnersList",
props: {
runners: Array
},
computed: {
formatRunners() {
const runnerItems = [];
for (const runner of this.runners) {
const newItem = {};
newItem.id = runner.id;
newItem.isPublic = runner.marathon.isPublic;
newItem.AvailableCpu = runner.availableResources.cores;
newItem.AvailableMemory = fileSize(runner.availableResources.memory);
runnerItems.push(newItem);
}
return runnerItems;
}
},
data() {
return {};
}
};
</script>
This is not a really aesthetic solution, but here is a quick workaround:
in your template, add this v-if condition:
<b-table v-if="haveResourcesLoaded" striped hover :items="formatRunners"></b-table>
then in your computed properties, add the corresponding one:
haveResourcesLoaded() {
if (this.runners.length > 0) {
return this.runners[0].availableResources !== undefined
}
return false
}
If you need to do it in a better and more controlled way, you should take a look at the documentation, the bus.isOnline() method might be what you're looking for.
It wasn't so much issue with the listing, as it was update function only getting called once in a minute. The final code is for listing runner is bellow.
<template>
<b-col>
<b-table v-if="runnersTable.length > 0" striped hover :items="runnersTable"></b-table>
</b-col>
</template>
<script>
const fileSize = require("filesize");
export default {
name: "RunnersList",
props: {
runners: Array
},
data() {
return {
haveResourcesLoaded: false
};
},
mounted() {},
computed: {
runnersTable() {
const runnerItems = [];
for (const runner of this.runners) {
const newItem = {
id: runner.id,
isPublic: runner.marathon.isPublic,
AvailableCpu: runner.availableResources.cores,
AvailableMemory: fileSize(runner.availableResources.memory)
};
runnerItems.push(newItem);
}
return runnerItems;
}
}
};
</script>

Iterate over data() returned value

My HTML code is like below
<ul>
<li v-for="item in values">{{ item }}</li>
</ul>
My vue.js code is like below
export default {
data() {
return {
values: {}
}
},
props: ['applicants', 'pageinfo'],
watch: {
applicants (val) {
EventBus.$on('click', function (skillName) {
this.values = val[0];
console.log(this.values); // I am getting output here.
});
},
},
}
I am trying to iterate over the values of val[0]. But I am not getting any output.
Either use arrow function like
applicants (val) {
EventBus.$on('click', (skillName) => {
this.values = val[0];
console.log(this.values); // I am getting output here.
});
},
or save the reference of this before the event handler
applicants (val) {
var _self = this;
EventBus.$on('click', function (skillName) {
_self.values = val[0];
console.log(this.values); // I am getting output here.
});
},

Why is my state being updated here?

I'm pretty new to React, but liking it so far. I'm building a large application, which is going well, except I've run into an issue. I'm building a list of responses to questions, and they can be deleted, but I also want to have a "Cancel" button so all unsaved changes can be reverted. What is confusing me is the cancel button reverts to the initial state for the name value, but not the responses. If I add in some console logging to the response deletion script, I would expect to see log lines 1 & 2 match, with 3 being different. However, I'm seeing that 1 is the original, but 2 & 3 match. Why is state being updated before I call setState, and why does updating state seem to update the my initial props?
EDIT: I added a jsFiddle
getInitialState: function() {
return {
name: this.props.question.name,
responses: this.props.question.responses,
};
},
handleCancelButtonClick: function(e) {
this.replaceState(this.getInitialState());
},
handleNameChange: function(e) {
this.setState({name: e.target.value});
},
handleResponseDeletion: function(e) {
var resp = this.state.responses;
var from = Number(e.target.value);
console.log(JSON.stringify(this.state.responses));
resp.splice(from, 1);
console.log(JSON.stringify(this.state.responses));
this.setState({responses: resp});
console.log(JSON.stringify(this.state.responses));
},
render: function() {
var key = "mp" + this.props.question.name;
var resp = [];
if (this.state.responses) {
this.state.responses.forEach(function(response, i) {
var rkey = "r_" + this.props.question.name + "_" + i;
resp.push(<ModalResponse response={response} key={rkey} value={i} deleteResponse={this.handleResponseDeletion} />);
}.bind(this));
}
return (
<layer id={this.props.question.name} style={questionModal} key={key}>
<h2>Edit {this.state.name}</h2>
<button onClick={this.handleCancelButtonClick}>Cancel</button>
<div class='form-group'>
<label for='client_name' style={formLabel}>Question Name:</label><br />
<input type='text' style={formControl} id='question_name' name='question_name' value={this.state.name} onChange={this.handleNameChange} required />
</div>
<div class='form-group'>
<label style={formLabel}>Responses:</label><br />
<ul style={responseList} type="response_list" value={this.props.qname}>
{resp}
</ul>
</div>
</layer>
);
}
});
The problem is that splice modifies original array. It means the one that belongs to the original question. So when you call getInitialState from within handleCancelButtonClick you get modified array.
To avoid this you need to somehow clone original data inside getInitialState. For example
getInitialState: function() {
//copy array and responses
const copy = resp => ({...resp})
return {
name: this.props.question.name,
responses: this.props.question.responses.map(copy)
};
}
Here's what I did to fix the issue:
handleResponseDeletion: function(e) {
var resp = []
var from = Number(e.target.value);
this.state.responses.forEach(function(res, i) {
if (i != from) {
resp.push(res);
}
});
this.setState({responses: resp});
},

React onClick fires multiple times on load and doesn't contain callback function in component props

I believe I have two basic problems, which are probably connected. I'm trying to place an event handler with a callback function on a nested component. It didn't seem to be doing anything, so I replaced the callback function with an alert of JSON.stringify(this.props) to see if that would shed any light. It illuminated two problems: 1) my callback function was not in the props. 2) the alert popped up 2 times on page load, but did not pop up on click, like it was supposed to. I'm working through this React tutorial. Here are the relevant components:
var App = React.createClass({
mixins: [Catalyst.LinkedStateMixin],
getInitialState: function(){
return {
fishes: {},
order: {}
}
},
componentDidMount: function(){
base.syncState(this.props.params.storeId + '/fishes', {
context: this,
state: 'fishes'
});
var localStorageRef = localStorage.getItem('order-' + this.props.params.storeId);
if(localStorageRef){
this.setState({
order: JSON.parse(localStorageRef)
});
}
},
componentWillUpdate: function(nextProps, nextState){
localStorage.setItem('order-' + this.props.params.storeId, JSON.stringify(nextState.order));
},
loadSamples: function(){
this.setState({
fishes: require('./sample-fishes.js')
});
},
addFish: function(fish){
var timestamp = (new Date()).getTime();
this.state.fishes['fish-' + timestamp] = fish;
this.setState({ fishes: this.state.fishes });
},
removeFish: function(key){
if(confirm("Are you sure you want to remove this fish?")){
this.state.fishes[key] = null;
this.setState({ fishes: this.state.fishes });
}
},
addToOrder: function(key){
this.state.order[key] = this.state.order[key] + 1 || 1;
this.setState({ order: this.state.order });
},
// <<<<<<<< the function I'm having trouble with >>>>>>>>
removeFromOrder: function(key){
alert('hi');
delete this.state.order[key];
this.setState({ order: this.state.order });
},
renderFish(key){
return <Fish key={key} index={key} details={this.state.fishes[key]} addToOrder={this.addToOrder}/>
},
render: function(){
return (
<div className="catch-of-the-day">
<div className="menu">
<Header tagline="Fresh Seafood Market"/>
<ul className="list-of-fish">
{/*{ Object.keys(this.state.fishes).map(this.renderFish) }*/}
{ Object.keys(this.state.fishes).length > 0 ? Object.keys(this.state.fishes).map(this.renderFish) : <li>No Fishes!</li> }
</ul>
</div>
// <<<<<<<< I pass the function through to the Order component >>>>>>>>
<Order fishes={this.state.fishes} order={this.state.order} removeFromOrder={this.removeFromOrder}/>
<Inventory fishes={this.state.fishes} addFish={this.addFish} removeFish={this.removeFish} loadSamples={this.loadSamples} linkState={this.linkState}/>
</div>
)
}
});
var Order = React.createClass({
renderOrder: function(key){
var fish = this.props.fishes[key];
var count = this.props.order[key];
// <<<<<<<< the onClick I'm having trouble with >>>>>>>>
var removeButton = <button onCLick={this.props.removeFromOrder.bind(null, key)}>×</button>
// var removeButton = <button onCLick={alert(JSON.stringify(this.props))}>×</button>
if(!fish) {
return <li key={key}>Sorry, that fish is no longer available! {removeButton}</li>
// return <li key={key}>Sorry, that fish is no longer available!</li>
}
return (
<li key={key}>
{count}lbs
{" " + fish.name}
<span className="price">{helpers.formatPrice(count * fish.price)} {removeButton}</span>
{/*<span className="price">{helpers.formatPrice(count * fish.price)}</span>*/}
</li>
)
},
render: function(){
var orderIds = Object.keys(this.props.order);
var total = orderIds.reduce((prevTotal, key)=>{
var fish = this.props.fishes[key];
var count = this.props.order[key];
var isAvailable = fish && fish.status === 'available';
if(isAvailable) {
return prevTotal + (count * parseInt(fish.price) || 0);
}
return prevTotal;
}, 0);
return (
<div className="order-wrap">
<h2 className="order-title">Your Order</h2>
<ul className="order">
{ orderIds.length > 0 ? orderIds.map(this.renderOrder) : ""}
<li className="total">
<strong>Total:</strong>
{helpers.formatPrice(total)}
</li>
</ul>
</div>
)
}
});
The props for Order should include: the available fishes with all of their details, the current order with a fish id and quantity, and the removeFromOrder callback. When I explore the component in React dev tools, it has all of these things.
When I replace the removeFromOrder callback with an alert of the props, what happens is:
- on click, nothing
- on page refresh, two alerts pop up: the props in the first include the current order and an empty fishes array, the props in the second include the current order and the populated fishes array. Neither show the removeFromOrder callback function, which appears to be undefined from the perspective of the event listener.
On a potentially related note, when I explore the component in React dev tools and hover over a list item in the Order, I get the following error: TypeError: node.getBoundingClientRect is not a function. I'm not sure if this is part of my problem; if it's not, I'm not too concerned about it, since it only seems to pop up when I hover over the element in dev tools.
Thank you for reading this long thing, and any help would be much appreciated!
As #azium pointed out, the problem was a simple typo: onCLick={alert()} should instead be onClick={() => alert()}. Facepalm.

React, adding components in component

I started to learn React and I hit first wall.
I have a list component which should display a list of rows + button for adding a new row.
All is in those 2 gists:
https://gist.github.com/matiit/7b361dee3f878502e10a
https://gist.github.com/matiit/8bac28c4d5c6ce3993c7
The addRow method is executed on click, because I can see the console.log, but no InputRows are added.
Can't really see why.
This is a little updated (dirty) code which doesn't work either.
Now it's only one file:
var InputList = React.createClass({
getInitialState: function () {
return {
rowCount: 1
}
},
getClassNames: function () {
if (this.props.type === 'incomes') {
return 'col-md-4 ' + this.props.type;
} else if (this.props.type === 'expenses') {
return 'col-md-4 col-md-offset-1 ' + this.props.type;
}
},
addRow: function () {
this.state.rowCount = this.state.rowCount + 1;
this.render();
},
render: function () {
var inputs = [];
for (var i=0;i<this.state.rowCount; i++) {
inputs.push(i);
}
console.log(inputs);
return (
<div className={ this.getClassNames() }>
{inputs.map(function (result) {
return <InputRow key={result} />;
})}
<div className="row">
<button onClick={this.addRow} className="btn btn-success">Add more</button>
</div>
</div>
);
}
});
this.render() doesn't do anything. If you look at the function, it simply does some calculations and returns some data (the virtual dom nodes).
You should be using setState instead of directly modifying it. This is cleaner, and allows react to know something's changed.
addRow: function () {
this.setState({rowCount: this.state.rowCount + 1});
},
Don't store list of components in state.
Instead store the income row count and expense row count in state.
Use click handler to increment these counts.
Use render method to generate required rows based on count.

Resources