Updating state in react using componentDidUpdate - reactjs

I cannot get the state to update in my code
I am having an issue wiith my componentDidUpdate() which does not update the state of assignments after making an API call
when updating assignments. When I update the expiration date of a particular assignment in my list, it makes an API call to the server and returns
true if the response succeeds. The only way to see the update change in the state is to refresh the page. componentDidUpdate()
is stuck in an infinite loop, can anyone identify the underlining cause for this?
Thanks for any help
import * as React from 'react';
import './BundleAssignments.less';
import { IBundles, featureAccessApi, IAssignmentsByFirm, IBundleAssignment } from '#afi/tfs';
import { Loader } from '#afi/tfs';
export interface IOwnProps {}
export interface IOwnState {
loadingBundles: boolean,
loadingAssignments?: boolean,
loadingUpdate?: boolean,
bundles: IBundles[],
assignments: IAssignmentsByFirm[],
expirationDate: string,
bundleId?: number | undefined
}
export class BundleAssignments extends React.Component<IOwnProps, IOwnState> {
constructor(props: IOwnProps) {
super(props);
this.state = {
loadingBundles: true,
bundles: [],
assignments: [],
expirationDate: "",
bundleId: undefined
};
}
public componentDidMount() {
this.loadBundles();
}
public componentDidUpdate(prevProps: IOwnProps, prevState: IOwnState)
{
if (prevState.assignments !== this.state.assignments && this.state.bundleId !== undefined){
this.loadBundleAssignments(this.state.bundleId);
}
}
public render() {
return (
<div className="bundle-assignments">
<h1>Bundle assignments</h1>
{
this.state.loadingBundles ? <Loader /> :
<>
<select onChange={e => this.onChangeSelectedBundle(e)}>
<option value="">-- Select a Bundle --</option>
{
this.state.bundles.map(b =>
<option key={b.id} value={b.id}>{b.name}</option>
)
}
</select>
{
this.state.assignments != null && this.state.assignments.length > 0 ?
(this.state.loadingAssignments || this.state.loadingUpdate) ? <Loader /> :
<>
<h1>Assignments</h1>
<div className="download">
<a href={"https://localhost:44301/api/v2/admin/featureBundle/download/" + this.state.bundleId}>Download Excel</a>
</div>
<table className="assignmentsTable">
{
this.state.assignments.map(a =>
<tr key={a.firmRef}>
<th>
<span>{a.firmName}</span><br />
<a href={"admin/teams/firm/" + a.firmRef}>View teams</a>
</th>
<td>
{
<ul id="entites">
{
a.entities.map(e =>
<li key={e.entityRef}>
<span>{e.entityName}</span>
</li>
)
}
</ul>
}
</td>
<td>
{
a.entities.map(e =>
<form key={e.entityRef} onSubmit={(event) => this.handleSubmit(event, e.bundleAssignment.entityRef, e.bundleAssignment.bundleId, e.bundleAssignment.entityTypeId)}>
<input type="datetime-local" name="expirationDate" defaultValue={e.bundleAssignment.expirationDate} onChange={this.handleInputChange} />
<input type="submit" value="Update" />
</form>
)
}
</td>
</tr>
)
}
</table>
</>
: null
}
</>
}
</div>
)
}
private loadBundles = () => {
featureAccessApi.bundles()
.then(response => this.loadBundlesSuccess(response.bundles));
}
private loadBundlesSuccess = (bundles: IBundles[]) => {
this.setState({ ...this.state,
...{
loadingBundles: false,
bundles: bundles
}
})
}
private onChangeSelectedBundle = (e: React.ChangeEvent<HTMLSelectElement>) => {
const bundleId = Number(e.target.value);
this.setState({ ...this.state, ...{ loadingAssignments: true, bundleId: bundleId } })
this.loadBundleAssignments(bundleId);
}
private handleSubmit = (e: React.FormEvent, entityRef: number, bundleId: number, entityTypeId: number) => {
e.preventDefault();
this.setState({ ...this.state, ...{ loadingUpdate: true }})
this.updateBundleAssignment(entityRef, bundleId, entityTypeId);
}
private handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({ ...this.state,
...{
[name]: value
}
})
}
private updateBundleAssignment = (entityRef: number, bundleId: number, entityTypeId: number) => {
const request: IBundleAssignment = {
entityRef: entityRef,
bundleId: bundleId,
entityTypeId: entityTypeId,
expirationDate: this.state.expirationDate
};
featureAccessApi.updateBundleAssignment(request)
.then(response => this.bundleAssignmentUpdateSuccess());
}
private bundleAssignmentUpdateSuccess = () =>
this.setState({ ...this.state, ...{ loadingUpdate: false }})
private loadBundleAssignments = (bundleId: number) => {
featureAccessApi.bundleAssignments(bundleId)
.then(response => this.loadBundleAssignmentsSuccess(response.assignmentsByFirms));
}
private loadBundleAssignmentsSuccess = (bundleAssignments: IAssignmentsByFirm[]) => {
this.setState({ ...this.state,
...{
loadingAssignments: false,
assignments: bundleAssignments
}
})
}
}

Comparing arrays with !== will only compare the reference of the arrays and not their contents, so every time you update the assignment array, loadBundleAssignments will be run again.
console.log([1,2] !== [1,2])
You could instead use e.g. Lodash isEqual to check if all the elements in the arrays match each other.
public componentDidUpdate(prevProps: IOwnProps, prevState: IOwnState) {
if (
!_.isEqual(prevState.assignments, this.state.assignments) &&
this.state.bundleId !== undefined
) {
this.loadBundleAssignments(this.state.bundleId);
}
}

Related

Is there a way to handle state in a form that is dynamically built based off of parameters sent from the back end

I have a page in react 18 talking to a server which is passing information about how to build specific elements in a dynamic form. I am trying to figure out how to manage state in a case where there are multiple selects/multiselects in the page. Using one hook will not work separately for each dropdown field.
Code is updated with the latest updates. Only having issues with setting default values at this point. Hooks will not initially set values when given.
import { Calendar } from 'primereact/calendar';
import { Dropdown } from 'primereact/dropdown';
import { InputSwitch } from 'primereact/inputswitch';
import { InputText } from 'primereact/inputtext';
import { MultiSelect } from 'primereact/multiselect';
import React, { useEffect, useState, VFC } from 'react';
import { useLocation } from 'react-router-dom';
import { useEffectOnce } from 'usehooks-ts';
import { useAppDispatch, useAppSelector } from 'redux/store';
import Form from '../components/ReportViewForm/Form';
import { getReportParamsAsync, selectReportParams } from '../redux/slice';
export const ReportView: VFC = () => {
const location = useLocation();
const locState = location.state as any;
const dispatch = useAppDispatch();
const reportParams = useAppSelector(selectReportParams);
const fields: JSX.Element[] = [];
const depList: any[] = [];
//const defaultValList: any[] = [];
//dynamically setting state on all dropdown and multiselect fields
const handleDdlVal = (name: string, value: string) => {
depList.forEach((dep) => {
if (name === dep.dependencies[0]) {
dispatch(getReportParamsAsync(currentMenuItem + name + value));
}
});
setState((prev: any) => {
return { ...prev, [name]: value };
});
};
//dynamically setting state on all calendar fields
const handleCalVal = (name: string, value: Date) => {
setState((prev: any) => {
return { ...prev, [name]: value };
});
};
//dynamically setting state on all boolean fields
const handleBoolVal = (name: string, value: boolean) => {
setState((prev: any) => {
return { ...prev, [name]: value };
});
};
/* function getInitVals(values: any) {
const defaultList: any[] = [];
values.forEach((param: any) => {
defaultList.push({ name: param.name, value: param.defaultValues[0] });
});
} */
const [state, setState] = useState<any>({});
const [currentMenuItem, setCurrentMenuItem] = useState(locState.menuItem.id.toString());
useEffectOnce(() => {}), [];
useEffect(() => {
if (reportParams?.length === 0) {
dispatch(getReportParamsAsync(currentMenuItem));
}
//reload hack in order to get page to load correct fields when navigating to another report view
if (currentMenuItem != locState.menuItem.id) {
window.location.reload();
setCurrentMenuItem(locState.menuItem.id.toString());
}
}, [dispatch, reportParams, currentMenuItem, locState, state]);
//dependency list to check for dependent dropdowns, passed to reportddl
reportParams.forEach((parameter: any) => {
if (parameter.dependencies !== null && parameter.dependencies[0] !== 'apu_id') {
depList.push(parameter);
}
});
//filter dispatched data to build correct fields with data attached.
reportParams.forEach((parameter: any, i: number) => {
if (parameter.validValuesQueryBased === true) {
if (parameter.validValues !== null && parameter.multiValue) {
const dataList: any[] = [];
parameter.validValues.map((record: { value: any; label: any }) =>
dataList.push({ id: record.value, desc: record.label }),
);
fields.push(
<span key={i} className='p-float-label col-12 mx-3 field'>
<MultiSelect
options={dataList}
name={parameter.name}
value={state[parameter.name]}
onChange={(e) => handleDdlVal(parameter.name, e.value)}
></MultiSelect>
<label className='mx-3'>{parameter.prompt.substring(0, parameter.prompt.indexOf(':'))}</label>
</span>,
);
} else if (parameter.validValues !== null) {
const dataList: any[] = [];
parameter.validValues.map((record: { value: any; label: any }) =>
dataList.push({ id: record.value, desc: record.label }),
);
fields.push(
<span key={i} className='p-float-label col-12 mx-3 field'>
<Dropdown
options={dataList}
optionValue='id'
optionLabel='desc'
name={parameter.name}
onChange={(e) => handleDdlVal(parameter.name, e.value)}
value={state[parameter.name]}
//required={parameter.parameterStateName}
placeholder={'Select a Value'}
></Dropdown>
<label className='mx-3'>{parameter.prompt.substring(0, parameter.prompt.indexOf(':'))}</label>
</span>,
);
}
} else if (parameter.parameterTypeName === 'Boolean') {
fields.push(
<span key={i} className='col-12 mx-3 field-checkbox'>
<InputSwitch
checked={state[parameter.name]}
id={parameter.id}
name={parameter.name}
onChange={(e) => handleBoolVal(parameter.name, e.value)}
></InputSwitch>
<label className='mx-3'>{parameter.prompt.substring(0, parameter.prompt.indexOf(':'))}</label>
</span>,
);
} else if (parameter.parameterTypeName === 'DateTime') {
//const date = new Date(parameter.defaultValues[0]);
fields.push(
<span key={i} className='p-float-label col-12 mx-3 field'>
<Calendar
value={state[parameter.name]}
name={parameter.name}
onChange={(e) => {
const d: Date = e.value as Date;
handleCalVal(parameter.name, d);
}}
></Calendar>
<label className='mx-3'>{parameter.prompt.substring(0, parameter.prompt.indexOf(':'))}</label>
</span>,
);
} else if (parameter.name === 'apu_id') {
return null;
} else {
fields.push(
<span key={i} className='p-float-label col-12 mx-3 field'>
<InputText name={parameter.name}></InputText>
<label className='mx-3'>{parameter.prompt.substring(0, parameter.prompt.indexOf(':'))}</label>
</span>,
);
}
});
const onSubmit = () => {
console.log(state);
};
return (
<Form onReset={null} onSubmit={onSubmit} initialValues={null} validation={null} key={null}>
{fields}
</Form>
);
};
enter code here

Edit list item in place (React)

based on simple To-Do app, I'd like to understand how I can modify text of list item in place. List item contains 2 divs, first one holds todo's text and second one contains icons (delete, edit). I tried to conditionally render either first div or input inside the li, file ListItem.js, but that didn't work for me.
App.js
class App extends React.Component {
state = {
items: [],
currentValue: '',
clearValue: false
};
submitFormHandler = event => {
event.preventDefault();
if (this.state.currentValue === '') return;
const updatedItems = [...this.state.items];
if (
updatedItems.filter(udtItem => udtItem.value === this.state.currentValue)
.length === 0
) {
updatedItems.push({
id: uuidv4(),
value: this.state.currentValue,
completed: false
});
}
this.setState({ items: updatedItems, clearValue: true });
localStorage.setItem('todos', JSON.stringify(updatedItems));
};
changeInputHandler = event => {
this.setState({
currentValue: event.target.value,
clearValue: false
});
};
deleteItem = id => {
const updatedItems = [...this.state.items].filter(item => item.id !== id);
this.setState({ items: updatedItems });
localStorage.setItem('todos', JSON.stringify(updatedItems));
};
editItem = (event, id) => {
event.stopPropagation();
//do something here
};
deleteAll = () => {
this.setState({ items: [] });
localStorage.removeItem('todos');
};
componentDidMount() {
let todos = localStorage.getItem('todos');
if (todos) {
this.setState({ items: JSON.parse(todos) });
}
}
render() {
const itemList = this.state.items.map(item => (
<ListItem
key={item.id}
data={item}
deleted={this.deleteItem}
edited={this.editItem}
></ListItem>
));
return (
<div className="App">
<img src={trashIcon} alt="Delete" onClick={this.deleteAll} />
<header className="header">To-Do List</header>
<div className="items">
<ul>{itemList}</ul>
</div>
<form onSubmit={this.submitFormHandler}>
<Input
val={this.state.currentValue}
changed={e => this.changeInputHandler(e)}
clear={this.state.clearValue}
/>
</form>
</div>
);
}
}
export default App;
ListItem.js
class ListItem extends Component {
state = {
crossCheck: false,
hidden: true
};
toggleCrossCheck = () => {
const storageItems = JSON.parse(localStorage.getItem('todos'));
storageItems.forEach(item => {
if (item.id === this.props.data.id) {
item.completed = !item.completed;
this.setState({ crossCheck: item.completed });
}
});
localStorage.setItem('todos', JSON.stringify(storageItems));
};
componentDidMount() {
this.setState({ crossCheck: this.props.data.completed });
}
render() {
let classList = 'icon-container';
if (!this.state.hidden) classList = 'icon-container open';
return (
<li
className={this.state.crossCheck ? 'item cross-check' : 'item'}
onClick={this.toggleCrossCheck}
onMouseEnter={() => this.setState({ hidden: false })}
onMouseLeave={() => this.setState({ hidden: true })}
>
<div className="item-text">{this.props.data.value}</div>
<div className={classList}>
<Icon
iconType={trashIcon}
altText="Delete"
clicked={() => this.props.deleted(this.props.data.id)}
></Icon>
<Icon
iconType={editIcon}
altText="Edit"
clicked={event => this.props.edited(event, this.props.data.id)}
></Icon>
</div>
</li>
);
}
}
export default ListItem;

Set value to state React js

I need a bit of help.
I am new to react, so I have stuck here. I have shared a sandbox box link. That Contains a Table. as below
| Toy | Color Available | Cost Available |
Now everything works perfectly. But I want to save the data of the table as below
The detail state should contain a list of row values of the table and the columnsValues should contain the checkbox value of Color Available and Cost Available
Example:
this.state.detail like
detail: [
{
toy : ...
color : ...
cost : ...
}
{
toy : ...
color : ...
cost : ...
}
...
...
...
]
this.state.columnsValues like
columnsValues: {
color : boolean
cost : boolean
}
Any experts please help me out. I am struggling from past few hours.
Thank you.
Sandbox link: https://codesandbox.io/s/suspicious-microservice-qd3ku?file=/index.js
just paste this code it is working .
check your console you'll get your desired output .
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table, Checkbox, Input } from "antd";
import { PlusCircleOutlined, MinusCircleOutlined } from "#ant-design/icons";
const { Column } = Table;
class ToyTable extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: [
{
key: 0,
toy: "asdf",
color: "black",
cost: "23"
}
],
count: 0,
colorSwitch: false,
costSwitch: false,
columnsValues: {
color: true,
cost: true
},
detail: []
};
}
componentDidMount(){
const count = this.state.dataSource.length;
this.setState({
count
})
}
handleAdd = () => {
const { dataSource } = this.state;
let count = dataSource.length;
const newData = {
key: count,
toy: "",
color: "",
cost: ""
};
this.setState({
dataSource: [...dataSource, newData],
count
});
};
handleDelete = key => {
const dataSource = [...this.state.dataSource];
this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
};
onChangecolor = (e, record) => {
let dataSource = this.state.dataSource;
let key = record.key;
dataSource[key].color = e.target.value;
this.setState({
dataSource
});
};
onChangeCost = (e, record) => {
let dataSource = this.state.dataSource;
let key = record.key;
dataSource[key].cost = e.target.value;
this.setState({
dataSource
});
};
onChangeToy = (e, record) => {
console.log("I am inside handleInputChange", e.target.value, record);
let dataSource = this.state.dataSource;
let key = record.key;
dataSource[key].toy = e.target.value;
this.setState({
dataSource
});
};
checkColor = e => {
this.setState({ colorSwitch: e.target.checked });
};
checkCost = e => {
this.setState({ costSwitch: e.target.checked });
};
render() {
const { dataSource } = this.state;
console.log(dataSource);
return (
<Table bordered pagination={false} dataSource={dataSource}>
<Column
title="Toy"
align="center"
key="toy"
dataIndex="toy"
render={(text, record) => (
<Input
component="input"
className="ant-input"
type="text"
value={record.toy}
onChange={e => this.onChangeToy(e, record)}
/>
)}
/>
<Column
title={() => (
<div className="row">
Color Available
<div className="col-md-5">
<Checkbox size="small" onChange={this.checkColor} />
</div>
</div>
)}
align="center"
dataIndex="color"
render={(text, record) => (
<Input
disabled={!this.state.colorSwitch}
value={record.color}
onChange={e => this.onChangecolor(e, record)}
component="input"
className="ant-input"
type="text"
/>
)}
/>
<Column
title={() => (
<div className="row">
Cost Available
<div className="col-md-5">
<Checkbox size="small" onChange={this.checkCost} />
</div>
</div>
)}
align="center"
dataIndex="color"
render={(text, record) => (
<Input
disabled={!this.state.costSwitch}
value={record.cost}
onChange={e => this.onChangeCost(e, record)}
component="input"
className="ant-input"
type="text"
/>
)}
/>
<Column
render={(text, record) =>
this.state.count !== 0 && record.key + 1 !== this.state.count ? (
<MinusCircleOutlined
onClick={() => this.handleDelete(record.key)}
/>
) : (
<PlusCircleOutlined onClick={this.handleAdd} />
)
}
/>
</Table>
);
}
}
ReactDOM.render(<ToyTable />, document.getElementById("container"));
This isn't an exact answer, but just as a general direction - you need something in the state to capture the values of the currently edited row contents, that you can then add to the final list. This is assuming once committed, you don't want to modify the final list.
Firstly, have an initial state that stores the values in the current row being edited
this.state = {
currentData: {
toy: '',
color: '',
..other props in the row
}
...other state variables like dataSource etc
}
Secondly, when the value in an input box is changed, you have to update the corresponding property in the currentData state variable. I see that you already have a handleInputChange function
For eg, for the input box corresponding to toy, you'd do
<input onChange={e => handleInputChange(e, 'toy')} ...other props />
and in the function itself, you'd update the currentData state variable, something like:
handleInputChange = (e, property) => {
const data = this.state.currentData
data[property] = e.target.value
this.setState({ currentData: data })
}
Finally, when you press add, in your handleAddFunction, you want to do two things:
1) use the currentData in state, that's been saving your current values and push them into the dataSource or details array
2) restore the currentData to the blank state, ready to track updates for the next row.
handleAdd = () => {
const { count, dataSource } = this.state;
const newData = {
key: count,
...this.state.newData,
};
this.setState({
dataSource: [...dataSource, newData],
count: count + 1,
currentData: {
toy: '',
// other default values
}
});
};

componentWillReceiveProps render multiple times

I am getting datas from my database using three different functions, but as I've seen componentWillReceiveProps is rerendering for three times in this case, which cause duplicating my elements in the frontend. How can I render it just once, or only object's props really change. Till now, my follows[] array objects are duplicating
class UserDashboard extends React.Component {
state = {
uid: this.props.userDetails.uid,
page: 1,
redirect: false,
target: 15,
selectedRole: 4,
selectedSourceRole: 1,
quote_nr: '',
source_id: '',
status_id: '',
cost: '',
rebate: '',
pageLoading: false,
date: '2222-01-02',
therapists:[],
globalTargets:[],
follows:[],
utc: new Date().toISOString().slice(0, 19).replace('T', ' '),
}
topProfilesUrl = 'therapists/top/profiles';
getGlobalTargets = 'owner/targets';
followActivities = 'user/follow/activities';
componentDidMount = () => {
const { getActivities,getFollowActivities,getTarget } = this;
getActivities();
getFollowActivities();
getTarget();
window.scrollTo(0, 0);
}
UNSAFE_componentWillReceiveProps = (newProps) => {
let apiDat = newProps.apiDat;
let apiData = newProps.apiData;
if (apiData.activities && apiData.activities.success ) {
let therapists = apiData.activities.therapists;
let hasMore = true;
console.log("unu")
if (therapists.length < 10) {
hasMore = false;
}
this.setState(() => ({
therapists: this.state.therapists.concat(therapists),
hasMore: hasMore,
pageLoading: false
}))
}
if (apiDat.targets && apiDat.targets.success) {
console.log("doi")
let globalTargets = apiDat.targets.globals;
let hasMore = true;
if (globalTargets.length < 10) {
hasMore = false;
}
this.setState(() => ({
globalTargets: this.state.globalTargets.concat(globalTargets),
}))
}
if (apiData.followActivities && apiData.followActivities.success) {
console.log("trei")
let follows = apiData.followActivities.follows;
let hasMore = true;
if (follows.length < 10) {
hasMore = false;
}
this.setState(() => ({
follows: this.state.follows.concat(follows),
}))
}
}
getTarget = () => {
this.setState({pageLoading: true}, () => { this.loadTargets() })
}
loadTargets = () => {
console.log("load")
this.props.actions.reqGetGlobalTargets({
body: {},
headers: null,
resource: `${this.getGlobalTargets}?page=${this.state.page}`
})
}
getFollowActivities= () => {
this.setState({pageLoading: true}, () => { this.loadFollowActivities() })
}
loadFollowActivities = () => {
console.log("load")
this.props.actions.reqGetFollowActivities({
body: {},
headers: null,
resource: `${this.followActivities}?page=${this.state.page}`
})
}
renderLeads = () => {
return (
this.state.globalTargets.slice(0,1).map( (t, idx) => (
t.daily_leads
))
)
}
renderSales = () => {
return (
this.state.globalTargets.slice(0,1).map( (t, idx) => (
t.daily_sales
))
)
}
renderRatio = () => {
return (
this.state.globalTargets.slice(0,1).map( (t, idx) => (
t.close_ratio
))
)
}
getActivities = () => {
this.setState({pageLoading: true}, () => { this.loadActivities() })
}
loadActivities = () => {
this.props.actions.reqGetTherapistsTopProfiles({
body: {},
headers: null,
resource: `${this.topProfilesUrl}?page=${this.state.page}`
})
}
renderActivities = () => {
const items = this.state.therapists.map( (t, idx) => (
<tr key={t.id} className="activity-display-table">
<td>Quote Nr.: {t.quote_nr}</td>
<td>Source: {t.source_id}</td>
<td>Status: {t.status_id}</td>
<td>Cost: ${t.cost}</td>
<td>Rebate: ${t.rebate}</td>
<td>Date: {t.date.slice(0,10).replace(/-/g,'-')}</td>
</tr>
))
return (
<div ref={0} className="therapist-list">
<h2>Your Past Entries: </h2>
{ items }
</div>
)
}
renderFollowActivities = () => {
const items = this.state.follows.map( (t, idx) => (
<tr key={t.id} className="activity-display-table">
<td>Quote Nr.: {t.quote_nr}</td>
<td>Source: {t.source_id}</td>
<td>Status: {t.status_id}</td>
<td>Cost: ${t.cost}</td>
<td>Rebate: ${t.rebate}</td>
<td>Date: {t.date.slice(0,10).replace(/-/g,'-')}</td>
</tr>
))
return (
<div ref={0} className="therapist-list">
{ items }
</div>
)
}
submitUrl = 'registerActivities';
handleChange = (eve) => {
let inputName = eve.target.name,
value = eve.target.value;
this.setState(() => {
return {[inputName]: value}
})
}
handleSubmit = () => {
this.setState(() => {
const acBody = {
quote_nr: this.state.quote_nr,
cost: this.state.cost,
source_id: this.state.selectedSourceRole,
status_id: this.state.selectedRole,
date: this.state.utc,
rebate: this.state.rebate,
user_id:this.state.uid,
}
this.props.actions.reqActionsUsers(acBody, this.submitUrl);
})
}
handleStatusChange = (event) => {
let statusId = event.target.value;
this.setState(() => ({
selectedRole: statusId
}))
}
handleSourceChange = (ev) => {
let statusId = ev.target.value;
this.setState(() => ({
selectedSourceRole: statusId
}))
}
render () {
console.log(this.state.follows);
return (
<MainWrapper>
<div id="user-dashboard">
<HeaderUser logoutRedirect="/signin"/>
<div className="page-background">
<SidebarUser page="dashboard"/>
{/* Page Content */}
<div className="inner-content">
<div className="top-row">
<h1>Salesperson Dashboard</h1>
</div>
<div className="second-row">
</div>
<div className="activity-table">
<table className="a">
<tr>
<th>Today's Targets ({this.state.utc.slice(0,10).replace(/-/g,'-')})</th>
<th>Weekly Targets</th>
<th>Bonus So Far This Week</th>
</tr>
<tr>
<td>0/{this.renderLeads()} Leads Handled</td>
<td>0/{this.renderLeads()*5} Leads Handled</td>
<td>$0 From Leads</td>
</tr>
<tr>
<td>0/{this.renderSales()} Sales</td>
<td>0/{this.renderSales()*5} Sales</td>
<td>$0 From Sales</td>
</tr>
<tr>
<td>0/{this.renderRatio()} Close Ratio</td>
<td>0/{this.renderRatio()*5} Close Ratio</td>
<td>$0 From Profit Share</td>
</tr>
</table>
</div>
<div>
<h2>Leads Due For A Followup</h2>
{ this.renderFollowActivities() }
</div>
<h2 className="activity">Add Activity</h2>
<div className="activity-menu">
<input type="text"
placeholder="Quote Number"
name="quote_nr"
onChange={this.handleChange}
/>
<select onChange={this.handleSourceChange}>
<option value="1">Phone</option>
<option value="2">Email</option>
<option value="3">Live Chat</option>
</select>
<select onChange={this.handleStatusChange}>
<option value="4">Lead</option>
<option value="5">Sold</option>
</select>
<input type="text"
placeholder="Cost"
name="cost"
onChange={this.handleChange}
/>
<input type="text"
placeholder={this.state.cost/20||("Recom. Rebate" + " $")}
name="recRebate"
readOnly
/>
<input type="text"
placeholder={this.state.cost/10||("Max Possible Rebate" + " $")}
name="maxRebate"
readOnly
/>
<input type="text"
placeholder="Final Rebate $"
name="rebate"
onChange={this.handleChange}
/>
</div>
<ButtonRoundGradient className="activity_button" text="Add Activity" onClick={this.handleSubmit}/>
{ this.renderActivities() }
</div>
</div>
</div>
</MainWrapper>
)
}
}
const mapStateToProps = state => ({
apiData: state.activities,
apiDat: state.targets,
userDetails: state.userDetails
})
function mapDispatchToProps(dispatch) {
return {
actions: {
reqGetGlobalTargets: bindActionCreators(reqGetGlobalTargets, dispatch),
reqGetFollowActivities: bindActionCreators(reqGetFollowActivities, dispatch),
reqGetTherapistsTopProfiles: bindActionCreators(reqGetTherapistsTopProfiles, dispatch),
reqFetchUserDetails: bindActionCreators(reqFetchUserDetails, dispatch),
reqActionsUsers: bindActionCreators(reqActionsUsers, dispatch),
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(UserDashboard)
ComponentWillRecieveProps would be called every time your state changes or your state changes, so if you want to stop duplicating, you should do this :
componentWillReceiveProps(nextProps, nextContext) {
if (JSON.stringify(nextProps.someProps.items) !== JSON.stringift(this.state.items)){
// do something
}
}
basically you should check if props and state of your component should react to the situation, then really render your application.
hope that helps

How to properly display JSON result in a table via ReactJS

I have this code which fetches data from an API and displays JSON response in a div. How do I display the JSON response in a table?
This is how I display it in div via status.jsx:
// some codings
render() {
const { status, isLocal } = this.props;
if(!isLocal()) {
return (
<div className="status">
<div className="status-text">
<b>Status</b> {status.text}<br />
<b>Title</b> status.textTitle} <br />
<b>Event</b> {status.textEvent}
</div>
</div>
)
}
}
I have tried displaying it in a table as per below but could not get it to be aligned properly
//some codings
render() {
const { status, isLocal } = this.props;
if(!isLocal()) {
return (
<table>
<tbody>
<th>Status</th>
<th>Title</th>
<th>Event</th>
<tr>
<td>{status.text} </td>
<td>{status.textTitle} </td>
<td>{status.textEvent}</td>
<td><button
className="btn btn-danger status-delete"
onClick={this.toggleDeleteConfirmation}
disabled={this.state.showDeleteConfirmation}
>
Delete
</button></td>
</tr></tbody>
</table>
)
}
}
Here is profile.jsx:
import React, { Component } from 'react';
import {
isSignInPending,
loadUserData,
Person,
getFile,
putFile,
lookupProfile
} from 'bs';
import Status from './Status.jsx';
const avatarFallbackImage = 'https://mysite/onename/avatar-placeholder.png';
const statusFileName = 'statuses.json';
export default class Profile extends Component {
constructor(props) {
super(props);
this.state = {
person: {
name() {
return 'Anonymous';
},
avatarUrl() {
return avatarFallbackImage;
},
},
username: "",
statuses: [],
statusIndex: 0,
isLoading: false
};
this.handleDelete = this.handleDelete.bind(this);
this.isLocal = this.isLocal.bind(this);
}
componentDidMount() {
this.fetchData()
}
handleDelete(id) {
const statuses = this.state.statuses.filter((status) => status.id !== id)
const options = { encrypt: false }
putFile(statusFileName, JSON.stringify(statuses), options)
.then(() => {
this.setState({
statuses
})
})
}
fetchData() {
if (this.isLocal()) {
this.setState({ isLoading: true })
const options = { decrypt: false, zoneFileLookupURL: 'https://myapi/v1/names/' }
getFile(statusFileName, options)
.then((file) => {
var statuses = JSON.parse(file || '[]')
this.setState({
person: new Person(loadUserData().profile),
username: loadUserData().username,
statusIndex: statuses.length,
statuses: statuses,
})
})
.finally(() => {
this.setState({ isLoading: false })
})
} else {
const username = this.props.match.params.username
this.setState({ isLoading: true })
lookupProfile(username)
.then((profile) => {
this.setState({
person: new Person(profile),
username: username
})
})
.catch((error) => {
console.log('could not resolve profile')
})
const options = { username: username, decrypt: false, zoneFileLookupURL: 'https://myapi/v1/names/'}
getFile(statusFileName, options)
.then((file) => {
var statuses = JSON.parse(file || '[]')
this.setState({
statusIndex: statuses.length,
statuses: statuses
})
})
.catch((error) => {
console.log('could not fetch statuses')
})
.finally(() => {
this.setState({ isLoading: false })
})
}
}
isLocal() {
return this.props.match.params.username ? false : true
}
render() {
const { handleSignOut } = this.props;
const { person } = this.state;
const { username } = this.state;
return (
!isSignInPending() && person ?
<div className="container">
<div className="row">
<div className="col-md-offset-3 col-md-6">
{this.isLocal() &&
<div className="new-status">
Hello
</div>
}
<div className="col-md-12 statuses">
{this.state.isLoading && <span>Loading...</span>}
{
this.state.statuses.map((status) => (
<Status
key={status.id}
status={status}
handleDelete={this.handleDelete}
isLocal={this.isLocal}
/>
))
}
</div>
</div>
</div>
</div> : null
);
}
}

Resources