Автоматически обновлять список с объектами в React - PullRequest
0 голосов
/ 08 марта 2020

Как автоматически обновить список объектами при добавлении в него нового объекта? У меня есть список ваших прошлых записей действий, как в примере с фотографией, и мне нужно обновлять его каждый раз, когда я Добавить действие . На данный момент добавленный элемент появляется только в том случае, если я обновлю sh страницу браузера. У меня есть объекты из базы данных. Поэтому, когда я добавляю элемент, сначала он добавляется в базу данных.

enter image description here

Надеюсь, я был достаточно ясен, и вы можете помочь мне, ребята.

onClick={this.handleUpdateSubmit} is the function which update the list 

Вот мой код

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: '',
    errorMessage: '',
    message: '',
    cost: '',
    rebate: '',
    pageLoading: false,
    date: '2222-01-02',
    therapists:[],
    globalTargets:[],
    follows:[],
    weekly:[],
    utc: new Date().toISOString().slice(0, 19).replace('T', ' '),
}

topProfilesUrl = 'therapists/top/profiles';
getGlobalTargets = 'owner/targets';
followActivities = 'user/follow/activities';
weeklyTarget= 'user/weekly/leads';

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 (this.props.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 (this.props.apiData !== newProps.apiData) {
        if (apiData.leads && apiData.leads.success) {
            let weekly = apiData.leads.weekly;
            let hasMore = true;
            console.log("unu")

            this.setState(() => ({
                weekly: this.state.weekly.concat(weekly),
                hasMore: hasMore,
                pageLoading: false
            }))
        }
    }

    if (this.props.apiDat !== newProps.apiDat) {

        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 (this.props.apiData !== newProps.apiData) {
        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
        ))
    )
}
weeklyLeads = () => {
    const nr = this.state.weekly.map( (t, idx) => (
        t.Leads||0
    ))
    return nr;
}
weeklySales = () => {
    const nr = this.state.weekly.map( (t, idx) => (
        t.Sales||0
    ))
    return nr;
}
getActivities = () => {
    this.setState({pageLoading: true}, () => { this.loadActivities() })
}

loadActivities = () => {
    this.props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${this.topProfilesUrl}?uid=${this.state.uid}`
    })
}
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>

    )
}
getleads = () =>{
    const id = "Lead";
    const dd =  this.state.utc.slice(0,10).replace(/-/g,'-');
    const count = this.state.therapists.filter((t) => t.status_id === id && t.date.slice(0,10).replace(/-/g,'-')===dd).length;
    const nb = this.state.therapists.filter((t) => t.date.slice(0,10).replace(/-/g,'-') === dd).length;

   // console.log(count);
    //console.log(nb);
    //console.log(dd);
    return count;
}

getsales = () =>{
    const status = "Sold";
    const dd =  this.state.utc.slice(0,10).replace(/-/g,'-');
    const nr = this.state.therapists.filter((t) => t.status_id === status && t.date.slice(0,10).replace(/-/g,'-')===dd).length;
 //   const nb = this.state.follows.filter((t) => t.date.slice(0,10).replace(/-/g,'-') === dd).length;
    console.log(nr);
    return nr;
}
submitUrl = 'registerActivities';
updateUrl = 'updateActivities';

handleChange = (eve) => {

    let inputName = eve.target.name,
        value = eve.target.value;

    this.setState(() => {
        return {[inputName]: value}
    })
}

handleSubmit = () => {
    this.setState({errors: []}, () => {

        const formValid = this.validateForm()

        if (!formValid) {
            return;
        }

        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);
    })
}

handleUpdateSubmit = () => {
    this.setState({errors: []}, () => {

        const formValid = this.validateForm()

        if (!formValid) {
            return;
        }

        const aBody = {
            id: this.state.id,
            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,
        }
        console.log(aBody);
        this.props.actions.reqUpdateAction(aBody, this.updateUrl);
    })
}

validateForm = () => {

    let formValid = true;

    if (this.state.quote_nr === '') {
        formValid = false;
        this.setState( () => ({
            errors: [
                {input: 'quote_nr'}
            ],
            errorMessage: 'Quote Number is mandatory',
        }))
    } else if (this.state.cost === '') {
        formValid = false;
        this.setState( () => ({
            errors: [
                {input: 'cost'}
            ],
            errorMessage: 'Cost is mandatory'
        }))
    } else if (this.state.rebate === '') {
        formValid = false;
        this.setState( () => ({
            errors: [
                {input: 'rebate'}
            ],
            errorMessage: 'Rebate is mandatory'
        }))
    }
    if (formValid === true) {
        this.setState( () => ({
            message: 'You Activity Has Been Added',
            errorMessage: ''
        }))
    }
    return formValid

}

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("weekly",this.weeklyLeads());
    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>{this.getleads()}/{this.renderLeads()} Leads Handled</td>
                                    <td>{this.weeklyLeads()}/{this.renderLeads()*5} Leads Handled</td>
                                    <td>$0 From Leads</td>
                                </tr>
                                <tr>
                                    <td>{this.getsales()}/{this.renderSales()} Sales</td>
                                    <td>{this.weeklySales()}/{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>
                        <p className="error-message">{this.state.errorMessage}</p>
                        <Popup
                        content={this.state.message}
                        on="click"
                        pinned
                        trigger={

                            <ButtonRoundGradient className="activity_button" text="Add Activity"
                                                 onClick={this.handleSubmit}/>
                        }
                        />
                        <Popup
                            content={"Activity Has Been Updated"}
                            on="click"
                            pinned
                            trigger={
                        <ButtonRoundGradient className="activity_button" text="Update Activity"  onClick={this.handleUpdateSubmit}/>
                            }
                        />
                        { this.renderActivities() }

                    </div>
                </div>
            </div>
        </MainWrapper>
    )
}

}

...