Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Hooks, state is reseting to initial state when called onChange is called inside Formatter #2133

Open
charleskatada opened this issue Apr 19, 2021 · 0 comments

Comments

@charleskatada
Copy link

Hi AllenFang, Thank you for all the support. I just have a question and I am not sure if I am doing it right or if it is even possible.

I am trying to change the value of my react hook state when OnChange is triggered inside formatter but for some reason the state always goes back to initial state ([]) when press any key and the current state is lost.

Here is some part o f my code.

import React, { useState, useEffect } from 'react'
import { connect } from 'react-redux'
// import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import BootstrapTable from 'react-bootstrap-table-next';
import paginationFactory from 'react-bootstrap-table2-paginator';

import {
Button,
CardSubtitle,
CardTitle,
Col,
TabPane,
Label,
Row,
InputGroup,
Input

} from "reactstrap"

import Switch from '@material-ui/core/Switch';
import CurrencyInput from 'react-currency-input-field';

import { setChequesCollections } from '../../../store/contracts/actions'
import { update } from 'lodash'

export const ChequeInfo = (props) => {

const [cheques,setCheques] = useState([

])


// const updateChequeNo = (e,index) =>{
//     e.preventDefault()
//     console.log(e.target.value)
//     console.log(index)
//     console.log(cheques)
//     // setCheques(tempArray)
    
// }


const updateChequeName = (e,index) =>{
    e.preventDefault()
    let tempArray = [...cheques]
    let tempElement  = [...tempArray[index]]
    tempElement.chequeName = e.target.value
    tempArray[index] = tempElement
    setCheques(tempArray)
  }

const updateBankName = (e,index) =>{
    e.preventDefault()
    let tempArray = [...cheques]
    let tempElement  = [...tempArray[index]]
    tempElement.bankName = e.target.value
    tempArray[index] = tempElement
    setCheques(tempArray)
}

const updateDate = (e,index) =>{
    e.preventDefault()
    let tempArray = [...cheques]
    let tempElement  = [...tempArray[index]]
    tempElement.date = e.target.value
    tempArray[index] = tempElement
    setCheques(tempArray)
}

const updateAmount = (e,index) =>{
    e.preventDefault()
    let tempArray = [...cheques]
    let tempElement  = [...tempArray[index]]
    tempElement.amount  = e.target.value
    tempArray[index] = tempElement
    setCheques(tempArray)
}



const [columns,setColumns] = useState([
    {
        dataField:'chequeNo',
        text:'Cheque No',
        formatExtraData:{cheques},
        formatter:(cell,row,rowIndex,formatExtraData) => (
                            <input
                                type="text"
                                className="form-control"
                                name={`chequeNo${row.id}`}
                                id={`chequeNo${row.id}`}
                                // defaultValue={}
                                onChange={()=>console.log(formatExtraData)}
                           />
        
                         )

    },
    {
        dataField:'chequeName',
        text:'NAME',
        formatExtraData:cheques,
        formatter:(cell,row,rowIndex,formatExtraData) => (
                            <input
                                type="text"
                                className="form-control"
                                name={`name ${row.id}`}
                                id={`name ${row.id}`}
                                // defaultValue={}
                                onChange={()=>console.log(formatExtraData)}
                           />
        
                         )

    },
    {
        dataField:'bankName',
        text:'Bank',
        formatExtraData:cheques,
        formatter:(cell,row,rowIndex,formatExtraData) => (
                            <input
                                type="text"
                                className="form-control"
                                name={`bankName${row.id}`}
                                id={`bankName${row.id}`}
                                // defaultValue={}
                                onChange={()=>console.log(formatExtraData)}
                           />
        
                         )

    },
    {
        dataField:'date',
        text:'DATE',
        formatExtraData:cheques,
        formatter:(cell,row,rowIndex,formatExtraData) => (
                            <input
                                type="text"
                                className="form-control"
                                name={`date${row.id}`}
                                id={`date${row.id}`}
                                // defaultValue={}
                                onChange={()=>console.log(formatExtraData)}
                           />
        
                         )

    },
    {
        dataField:'amount',
        text:'AMOUNT',
        formatExtraData:cheques,
        formatter:(cell,row,rowIndex,formatExtraData) => (
                            <input
                                type="text"
                                className="form-control"
                                name={`bankName${row.id}`}
                                id={`bankName${row.id}`}
                                // defaultValue={}
                                onChange={()=>console.log(formatExtraData)}
                           />
        
                         )

    }
    

])





var chequeDate = new Date(props.startDate)

const handlePaymentNo = (e) => {
    e.preventDefault()
    setCheques([])
    const count = e.target.value
    var chequeTimeZoneDiff = props.startDate.getTimezoneOffset().toString().substring(1)
    // var chequeTimeZoneDiff = props.startDate().getTimeZoneOffset().toString().substring(1)
    chequeDate.setHours(0, Number(chequeTimeZoneDiff), 0)
    const duration = Math.round(props.endDate - props.startDate)
    const calculateDuration = duration / (1000 * 60 * 60 * 24)

    switch (count) {

        case '1':

        setCheques(chequeArray=>[...chequeArray,{
            index: 0,
            cleared: false,
            contractNo: props.contractNo,
            chequeName: props.selectedTenant.name,
            chequeNo: '00000',
            bankName: '',
            date: new Date(props.startDate).toString(),
            amount: props.selectedProperty.amount,
            propertyId: props.selectedProperty.propertyId
        }])

        break

        default:

            for (let a = 1; a <= count; a++) {

                if (a === 1) {
              
                    setCheques(chequeArray =>[...chequeArray,{
                        index: 0,
                        cleared: false,
                        contractNo: props.contractNo,
                        chequeName: props.selectedTenant.name,
                        chequeNo: '00000',
                        bankName: '-',
                        date: new Date(props.startDate).toString(),
                        amount: props.selectedProperty.amount / count,
                        propertyId: props.selectedProperty.propertyId
                    }])
        
                }
                else {
                    chequeDate.setDate(
                        chequeDate.getDate() + (calculateDuration / count) * (a - 1) - 1
                    )
                    setCheques(chequeArray => [...chequeArray,{
                        index: a + 1,
                        cleared: false,
                        contractNo: props.contractNo,
                        chequeName: props.selectedTenant.name,
                        chequeNo: '00000',
                        bankName: '-',
                        date: new Date(chequeDate).toString(),
                        amount: props.selectedProperty.amount / count ,
                        propertyId: props.selectedProperty.propertyId
                    }])
              
                    console.log(cheques)
                    chequeDate = new Date(props.startDate)
                }
            }
    }


    props.setChequesCollections(cheques)
    // chequeCollections = []
    console.log(chequeCollections)
    console.log(props.chequesCollection)
    console.log(cheques)

}


const options = {
    filterType: 'checkbox'
}

useEffect(() => {
}, [])





return (
    <TabPane tabId="2">
        <div className="dashBordContainer">
            <Row>
                <Col sm="12" lg="4">
                    <label htmlFor="paymentNo" className="control-label">SELECT PAYMENT</label>
                    <InputGroup>
                        <select onChange={handlePaymentNo} name="paymentNo" id="paymentNo" className="form-control">
                            <option value=''>-Select-</option>
                            <option value={1} id='one'>1</option>
                            <option value={2} id='two'>2</option>
                            <option value={3} id='three'>3</option>
                            <option value={4} id='four'>4</option>
                            <option value={5} id='five'>5</option>
                            <option value={6} id='six'>6</option>
                            <option value={7} id='seven'>7</option>
                            <option value={8} id='eight'>8</option>
                            <option value={9} id='nine'>9</option>
                            <option value={10} id='ten'>10</option>
                            <option value={11} id='eleven'>11</option>
                            <option value={12} id='twelve'>12</option>
                        </select></InputGroup>
                </Col>
            </Row>
            <div className="marginTop30" />





            <BootstrapTable
                keyField='index' 
                data={ cheques } 
                columns={ columns } 
                pagination={paginationFactory()}
                />



            {/* <MUIDataTable
                title={"CHEQUE LIST"}
                data={cheques}
                columns={columns}
                options={options}
            /> */}





        </div>

    </TabPane>
)

}

const mapStateToProps = state => {

const { contract, selectedProperty, selectedTenant, contractNo, startDate, endDate, chequesCollection } = state.Contracts

return {
    contract,
    selectedProperty,
    selectedTenant,
    contractNo,
    startDate,
    endDate,
    chequesCollection
}

}

const mapDispatchToProps = {
setChequesCollections
}

export default connect(mapStateToProps, mapDispatchToProps)(ChequeInfo)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant