Reactjs: How to update component when a new prop comes up? - javascript

I want to update/re-render the component after a new update comes up. All I am doing is:
I have a list of dealers for a casino game, what I want is to add a new dealer, and once the new dealer is added then display it in the view. It is actually happening, but in order for me to see the new dealer, I have to reload the page.
I am not updating the state, I am working with this.props. Look at my code
#connectToStores
export default class Dealers extends Component {
constructor (props) {
super(props);
this.state = {}
}
componentWillMount () {
GetDealersActions.getDealers();
}
static getStores () {
return [ GetDealersStore, CreateDealersStore ];
}
static getPropsFromStores () {
return {
...GetDealersStore.getState(),
...CreateDealersStore.getState(),
}
}
render () {
return (
<div>
{!!this.props.dealerData ?
this.props.dealerData.dealersData.map((dealer) => {
return (here I am rendering what I need);
: <p>Loading . . .</p>
</div>
}
_addDealer = () => {
CreateDealersActions.createDealer({
DealerName : this.refs.DealerName.getValue(),
CardId : this.refs.CardId.getValue(),
NickName : this.refs.NickName.getValue(),
});
}
}
as you see the component above in the code is doing the initial rendering properly, the problem comes up when you hit _addDealer(), which is not updating the component, you should reload the page in order to see the new item in the view.
If you do a console.log(this.props); within _addDealer(), you will get something like this
{params: Object, query: Object, dealerData: Object, newDealerData: null}
where dealerData holds the full data of the dealers in the view but you can't see there the new dealer created. And newDealerData remains null
so, what do you think I should do in order to update the component everytime a new prop/dealer comes up ? or how do I update the props? which is the proper method in this situation ?
here is the full code for stores and actions just in case
action
#createActions(flux)
class CreateDealersActions {
constructor () {
this.generateActions('createDealerSuccess', 'createDealerFail');
}
createDealer (data) {
const that = this;
that.dispatch();
axios.post(`${API_ENDPOINT}/create-dealer/create-dealer`, data)
.then(function success (data) {
that.actions.createDealerSuccess({data});
})
}
};
store
#createStore(flux)
class CreateDealersStore {
constructor () {
this.state = {
newDealerData : null,
};
}
#bind(CreateDealersActions.createDealerSuccess)
createDealerSuccess (data) {
this.setState({
newDealerData : data.response.config.data,
});
}
}
the Dealers component is within a tab named management, which is this one:
const menuItems = [
{ route : 'dealers', text : 'Dealers' },
{ route : 'game-info', text : 'Game Info' },
{ route : 'player-info', text : 'Players Info' },
{ route : 'money', text : 'Money' }
];
export default class Management extends React.Component {
static propTypes = {
getActivePage : React.PropTypes.func,
menuItems : React.PropTypes.arrayOf(React.PropTypes.object),
}
static contextTypes = {
router : React.PropTypes.func,
}
render () {
return (
<div>
<TabsMainMenu menuItems={menuItems} getActivePage={this._getActivePage} />
<RouteHandler />
</div>
);
}
_getActivePage = () => {
for (const i in menuItems) {
if (this.context.router.isActive(menuItems[i].route)) return parseInt(i, 10);
}
}
}

Related

How to dynamic change state in another vuex component?

I've got a problem with state in component. I have websocket and over it come changes, which I put it in some state. It's ok in one component, it dynamically changes value. But, when I go to the next component (vue-router). Its state changes as well, but is not dynamic. hmmmmm... in console.log changes coming, but not change value in another component.
How can I make it?
Let's see some code:
Here my action, with change states
actions: {
play(ctx, array){
axios.get('http://localhost/task_run?task_id='+array.id)
var conn = new WebSocket('ws://localhost:8080', "protocol");
conn.onmessage = function (ev) {
ctx.commit('procent', {key:array.key, val:ev.data});
ctx.commit('procentOne', {key:array.key, val:ev.data});
console.log('Message: ', ev);
};
},
},
mutations: {
procent(state, val){
var array = JSON.parse(val.val);
state.process[val.key] = array.procent;
state.processOnePersone[array.comp] = array.procent;
}
},
state: {
process: [],
processOnePersone:[],
},
getters: {
process(state){
return state.process
},
processOnePersone(state){
return state.processOnePersone;
}
}
I have one compenent, where it works
<v-progress-circular
:rotate="-90"
:size="50"
:width="5"
:value="process[key]"
color="primary"
>
{{ process[key] }}
</v-progress-circular>
<script>
import {mapGetters} from 'vuex';
export default {
name: 'taskListComponent',
computed: {
...mapGetters(['process',]),
},
}
And component where it doesn't work
<v-progress-circular
:rotate="-90"
:size="50"
:width="5"
:value="processOnePersone[key]"
color="primary"
>
{{ processOnePersone[key] }}
</v-progress-circular>
<script>
import {mapGetters} from 'vuex';
export default {
name: 'queueComponent',
computed: {
...mapGetters(['processOnePersone',]),
},
}

Update ngrx selector inside ngOnChanges

I have a parent component (B) that is getting data from it's parent input (A)
(C) have is (B) child component.
Inside (B) I'm having a selector that gets data from the store.
export class BComponent implements OnChanges {
#Input() branchId;
ngOnChanges() {
this.selectedDataByBranch$ = this.store.pipe(
select(selectBranchDirections, { branchId: this.branchId, dir: this.selectedDirection })
);
this.selectedDataByBranch$.subscribe(selectedDataByBranch => {
this.trainsDatasets = this.getDatasets(selectedDataByBranch);
this.lineChart.data.datasets = this.trainsDatasets ? this.trainsDatasets : [];
this.lineChart.update();
});
directionChanged(event) {
this.selectedDirection = event;
this.selectedDataByBranch$ = this.store.pipe(
select(selectBranchDirections, { branchId: this.branchId, dir: this.selectedDirection })
);
}
}
directionChanged is the Output event that I get from (C)
The issue this that selectedDataByBranch subscription is not getting the new data update triggered inside selectedDataByBranch$
I have also tried this way
directionChanged(event) {
this.selectedDirection = event;
select(selectBranchDirections, { branchId: this.branchId, dir: this.selectedDirection });
}
What i could suggest is. Turn your parameters into a Subject then merge with the store selection, in your directionChanged(event) method provide value to subject.
So your final code will be something like this:
export class BComponent implements OnChanges {
#Input() branchId;
criterias$= new Subject<{branchId:number,dir:number}>;
ngOnChanges() {
this.selectedDataByBranch$ = this.criterias$.pipe(mergeMap(criteria=> this.store.pipe(
select(selectBranchDirections, { branchId: criteria.branchId, dir: this.searchDirection})
)));
this.selectedDataByBranch$.subscribe(selectedDataByBranch => {
this.trainsDatasets = this.getDatasets(selectedDataByBranch);
this.lineChart.data.datasets = this.trainsDatasets ? this.trainsDatasets : [];
this.lineChart.update();
});
this.criterias$.next({branchId:this.branchId,dir:this.sortDirection}); // init first call
}
directionChanged(event) {
this.selectedDirection = event;
this.criterias$.next({ branchId: criteria.branchId, dir: this.searchDirection}});
);
}
}
This stackblitz tries to materialize what i say.

How to pass function from statefull to stateless component?

I want to pass the function from stateful component to stateless component below is my code.
below is stateless code
const ProductsGridItem = props => {
const { result } = props;
const source = result._source;
return (
<ProductCard
ProductName={source.productName}
ProductGuid={source.productGuid}
Key={source.productGuid}
ProductStatus={source.status}
DecimalPrecision={decimalValue}
IsActive={source.isActive}
Image={source.imageName}
ProductCode={source.productCode}
MinPrice={source.minPrice}
Ratings={source.ratings}
CurrencySymbol={source.currencySymbol}
SupplierGuid={source.supplierGuid}
Type="grid"
ListBucketDetails={basketDetails}
WishListDetails={wishListDetails}
CompanyName={source.companyName}
BuyingWindowStatus={source["buyingwindowstatus.raw"]}
NewArrival={source["newarrival_raw.raw"]}
/>
);
};
and below this my class method starts that is stateful code starts.
class ProductListingPage extends Component {
constructor(props) {
super(props);
this.state = {
resources: [],
isFeatureAvailable: false,
loading: false,
decimalPrecesion: "",
filterList: [],
productBucketList: [],
open: false,
rating: 1,
companyGuid: null,
showMobileFilter: false,
dataEmpty: false
};
}
handleDrawerOpen = () => {
this.setState({ open: true });
};
}
I want to pass the handleDrawerOpen in ProductCard component. Could you please help how to do this?
I can fix this issue by moving const ProductsGridItem in class but my seniors not allowing me to do this. I dont know why. Both code are in same file. Please help.
EDITED:
In render the stateless component is using like below
<ViewSwitcherHits
hitsPerPage={16}
sourceFilter={[
"productName",
"productCode",
"imageName",
"manufacturerName",
"productGuid",
"tagAttributes",
"status",
"isActive",
"minPrice",
"ratings",
"currencySymbol",
"supplierGuid",
"companyName",
"buyingwindowstatus.raw",
"listproductsubcategory",
"newarrival_raw.raw"
]}
hitComponents={[
{
key: "grid",
title: getLabelText(
resources.filter(x => {
return x.resourceKey === "grid";
})[0],
"Grid"
),
itemComponent: ProductsGridItem,
InitialLoaderComponent: InitialLoaderComponent,
defaultOption: true
},
{
key: "list",
title: getLabelText(
resources.filter(x => {
return x.resourceKey === "list";
})[0],
"List"
),
itemComponent: ProductsListItem,
InitialLoaderComponent: InitialLoaderComponent
}
]}
scrollTo="body"
/>
In Hitcomponents - itemComponent: ProductsGridItem, I'm using Searchkit ViewSwitcherHits
I assume ProductListingPage's render (which you haven't shown) uses ProductsGridItem. In that location, you'd pass this.handleOpen:
<ProductsGridItem handleOpen={this.handleOpen} YourOtherStuffHere />
Within ProductsGridItem, you'd pass that on to ProductsGrid:
return (
<ProductCard
handleOpen={props.handleOpen}
YourOtherStuffHere
/>
);
Some style rules suggest not using props. within the JSX for child components. If your in-house style rules say not to do that, you can put handleOpen in an initial destructuring of props:
const ProductsGridItem = props => {
const { result: {_source: source}, handleOpen } = props;
return (
<ProductCard
handleOpen={handleOpen}
ProductName={source.productName}
ProductGuid={source.productGuid}
Key={source.productGuid}
ProductStatus={source.status}
DecimalPrecision={decimalValue}
IsActive={source.isActive}
Image={source.imageName}
ProductCode={source.productCode}
MinPrice={source.minPrice}
Ratings={source.ratings}
CurrencySymbol={source.currencySymbol}
SupplierGuid={source.supplierGuid}
Type="grid"
ListBucketDetails={basketDetails}
WishListDetails={wishListDetails}
CompanyName={source.companyName}
BuyingWindowStatus={source["buyingwindowstatus.raw"]}
NewArrival={source["newarrival_raw.raw"]}
/>
);
};

Updating VueJS component data attributes when prop updates

I'm building a VueJS component which needs to update the data attributes when a prop is updated however, it's not working as I am expecting.
Basically, the flow is that someone searches for a contact via an autocomplete component I have, and if there's a match an event is emitted to the parent component.
That contact will belong to an organisation and I pass the data down to the organisation component which updates the data attributes. However it's not updating them.
The prop being passed to the organisation component is updated (via the event) but the data attibute values is not showing this change.
This is an illustration of my component's structure...
Here is my code...
Parent component
<template>
<div>
<blink-contact
:contact="contact"
v-on:contactSelected="setContact">
</blink-contact>
<blink-organisation
:organisation="organisation"
v-on:organisationSelected="setOrganisation">
</blink-organisation>
</div>
</template>
<script>
import BlinkContact from './BlinkContact.vue'
import BlinkOrganisation from './BlinkOrganisation.vue'
export default {
components: {BlinkContact, BlinkOrganisation},
props: [
'contact_id', 'contact_name', 'contact_tel', 'contact_email',
'organisation_id', 'organisation_name'
],
data () {
return {
contact: {
id: this.contact_id,
name: this.contact_name,
tel: this.contact_tel,
email: this.contact_email
},
organisation: {
id: this.organisation_id,
name: this.organisation_name
}
}
},
methods: {
setContact (contact) {
this.contact = contact
this.setOrganisation(contact.organisation)
},
setOrganisation (organisation) {
this.organisation = organisation
}
}
}
</script>
Child component (blink-organisation)
<template>
<blink-org-search
field-name="organisation_id"
:values="values"
endpoint="/api/v1/blink/organisations"
:format="format"
:query="getQuery"
v-on:itemSelected="setItem">
</blink-org-search>
</template>
<script>
export default {
props: ['organisation'],
data() {
return {
values: {
id: this.organisation.id,
search: this.organisation.name
},
format: function (items) {
for (let item of items.results) {
item.display = item.name
item.resultsDisplay = item.name
}
return items.results
}
}
},
methods: {
setItem (item) {
this.$emit('organisationSelected', item)
}
}
}
</script>
How can I update the child component's data properties when the prop changes?
Thanks!
Use a watch.
watch: {
organisation(newValue){
this.values.id = newValue.id
this.values.search = newValue.name
}
}
In this case, however, it looks like you could just use a computed instead of a data property because all you are doing is passing values along to your search component.
computed:{
values(){
return {
id: this.organisation.id
search: this.organisation.name
}
}
}

ReactJS: onClick change element

I've just started learning React and have a question.
I want to do the following:
If a user clicks on a paragraph I want to change the element to an input field that has the contents of the paragraph prefilled.
(The end goal is direct editing if the user has certain privileges)
I'm come this far but am totally at a loss.
var AppHeader = React.createClass({
editSlogan : function(){
return (
<input type="text" value={this.props.slogan} onChange={this.saveEdit}/>
)
},
saveEdit : function(){
// ajax to server
},
render: function(){
return (
<header>
<div className="container-fluid">
<div className="row">
<div className="col-md-12">
<h1>{this.props.name}</h1>
<p onClick={this.editSlogan}>{this.props.slogan}</p>
</div>
</div>
</div>
</header>
);
}
});
How can I override the render from the editSlogan function?
If I understand your questions correctly, you want to render a different element in case of an "onClick" event.
This is a great use case for react states.
Take the following example
React.createClass({
getInitialState : function() {
return { showMe : false };
},
onClick : function() {
this.setState({ showMe : true} );
},
render : function() {
if(this.state.showMe) {
return (<div> one div </div>);
} else {
return (<a onClick={this.onClick}> press me </a>);
}
}
})
This will change the components state, and makes React render the div instead of the a-tag. When a components state is altered(using the setState method), React calculates if it needs to rerender itself, and in that case, which parts of the component it needs to rerender.
More about states
https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html
You can solve it a little bit more clear way:
class EditableLabel extends React.Component {
constructor(props) {
super(props);
this.state = {
text: props.value,
editing: false
};
this.initEditor();
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
initEditor() {
this.editor = <input type="text" defaultValue={this.state.text} onKeyPress={(event) => {
const key = event.which || event.keyCode;
if (key === 13) { //enter key
this.save(event.target.value)
}
}} autoFocus={true}/>;
}
edit() {
this.setState({
text: this.state.text,
editing: true
})
};
save(value) {
this.setState({
text: value,
editing: false
})
};
componentDidUpdate() {
this.initEditor();
}
render() {
return this.state.editing ?
this.editor
: <p onClick={this.edit}>{this.state.text}</p>
}
}
//and use it like <EditableLabel value={"any external value"}/>;

Categories

Resources