1
votes

I am using componentDidUpdate for calling a certain function when my props change.

the problem is that I am unable to compare it to prevState, because prevState also shows the updated state. So, I am not sure now how to compare new and old state.

why is this happening?

Here's the code

componentDidUpdate(prevProps,prevState){
        console.log('prevProps',prevProps);
        console.log('prevstate : ',prevState.urls.length);
        console.log('prevProps : ',prevProps.urls.length);
        console.log('new props in canvas :',this.props.urls.length);

    }

now, i have removed the rest of the code, but in the console logs I can see that the value of urls length is coming as same in both prevState and the props. the problem is that prevProps are showing the same value as current props and the prevState is showing the same value as current State. so, I am kinda bewildered about how to compare!

can you tell why? is this a bug??

I tried it with componentWillReceiveProps too earlier, but there also the same problem was coming up.

just to show how /where/when I am setting state

import React, { Component } from 'react';
import { Modal,Button,Icon,Select,Input,Row,Col,Spin} from 'antd';
//import { connect } from 'dva';
import SortableComp from './SortableComp';
import ViewPdfModal from './ViewPdfModal';
import SaveEditedFiles from './SaveEditedFiles';
import TripsForm from '../../routes/Trips/TripsForm';
import {getRequest,postRequest,successNotification,errorNotification} from '../../utils/server-request';
import styles from '../../routes/Trips/EditPdfDetailsModal.less';

export default class CanvasRender extends Component{
    constructor(props){
        super(props);
        this.state={
            urls:this.props.urls,
            urlsOrder:[],
            imgsrc:[],
            viewFileModal:false
        }
        this.canvasRefs = {}
        this.imageRefs = {}
    }

    componentDidMount(){
        console.log('canvas mounted');
        setTimeout(this.pdfConversion(this.props.urls),7000);
       let urls = this.props.urls;
      let urlsOrder = [];
       urls.map((item)=>{
        let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
        if(this.props.type === 'maildoc'||this.props.type==='itinerary'||this.props.item && this.props.item.doctype === 'important' && this.props.item.doctypes && this.props.item.doctypes === 'emaildoc'){
            newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
        }else if(this.props.type === 'agency'){
            newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
        }else if(this.props.type === 'clients'){
            newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
        }
        urlsOrder.push(newItem);
       });
       this.setState({
           urlsOrder

       });
       /*
       if(this.props.getNewOrderEditPdf){
        this.props.getNewOrderEditPdf(urlsOrder);
    }

    this.props.dispatch({
        type: 'global/savePdfOrder',
        payload: urlsOrder
      });
        */
    }

    componentDidUpdate(prevProps,prevState){
        console.log('prevProps',prevProps);
        console.log('prevstate : ',prevState.urls.length);
        console.log('new props in canvas :',this.props.urls.length);
        if(prevState.urls.length!= this.state.urlsOrder.length){
            console.log('new props in canvas in IF :',this.props.urls);
            let urls = this.props.urls;
            let urlsOrder = [];
            urls.map((item)=>{
                let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
                if(this.props.type === 'maildoc'||this.props.type==='itinerary'||this.props.item && this.props.item.doctype === 'important' && this.props.item.doctypes && this.props.item.doctypes === 'emaildoc'){
                    newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
                }else if(this.props.type === 'agency'){
                    newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
                }else if(this.props.type === 'clients'){
                    newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
                }
                urlsOrder.push(newItem);
            });
            this.setState({
                urlsOrder                
            });

            this.pdfConversion(this.props.urls);
        }//end of if
    }//end of didupdate

    // static getDerivedStateFromProps(nextProps, prevState){
    //     console.log('props urls length :',  nextProps.urls.length);
    //     console.log('state urls length :',  prevState.urls.length);
    //     if(nextProps.urls.length!= prevState.urls.length){
    //         console.log('new props in canvas in IF :',nextProps.urls);
    //                 let urls = nextProps.urls;
    //                 let urlsOrder = [];
    //                 urls.map((item)=>{
    //                     let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
    //                     if(nextProps.type === 'maildoc'||nextProps.type==='itinerary'||nextProps.item && nextProps.item.doctype === 'important' && nextProps.doctypes && nextProps.item.doctypes === 'emaildoc'){
    //                         newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
    //                     }else if(nextProps.type === 'agency'){
    //                         newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
    //                     }else if(nextProps.type === 'clients'){
    //                         newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
    //                     }
    //                     urlsOrder.push(newItem);
    //                 });

    //       return { 
    //         urlsOrder,
    //         urls:nextProps.urls
    //     };
    //    }
    //    else return null;
    //  }



    // componentWillReceiveProps(nextProps){
    //     console.log('props urls length :',  nextProps.urls.length);
    //     console.log('state urls length :',  this.state.urls.length);

    //     if(nextProps.urls.length!= this.state.urls.length){
    //         console.log('new props in canvas in IF :',nextProps.urls);
    //         let urls = this.props.urls;
    //         let urlsOrder = [];
    //         urls.map((item)=>{
    //             let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
    //             if(nextProps.type === 'maildoc'||nextProps.type==='itinerary'||nextProps.item && nextProps.item.doctype === 'important' && nextProps.doctypes && nextProps.item.doctypes === 'emaildoc'){
    //                 newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
    //             }else if(nextProps.type === 'agency'){
    //                 newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
    //             }else if(nextProps.type === 'clients'){
    //                 newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
    //             }
    //             urlsOrder.push(newItem);
    //         });
    //         this.setState({
    //             urlsOrder,
    //             urls:nextProps.urls
    //         });

    //         this.pdfConversion(nextProps.urls);
    //         setTimeout(nextProps.hideLoading(),2000);

    //     }
    //     /*
    //     this.setState({
    //         urls:newUrls
    //     },()=>{
    //         this.pdfConversion(newUrls);
    //     });
    //     */ 
    // }

    pdfLoop = (item,index) => {
        var that = this;
        PDFJS.getDocument(item).then(function getPdfHelloWorld(pdf) {
             //
             // Fetch the first page
             console.log('url is : ',item);
             pdf.getPage(1).then(function getPageHelloWorld(page) {
               var scale = 0.5;
               var viewport = page.getViewport(scale);


                   let cref = 'canvas'+index;
                   let imgref ='img'+index;
                   console.log('cref no : ',cref);
                   console.log('img no : ',imgref);

                   // Prepare canvas using PDF page dimensions
                   //
                   var canvas = that.canvasRefs[cref];
                   //let imagez = that.imageRefs[imgref];
                   var context = canvas.getContext('2d');
                   context.globalcompositeoperation = 'source-over';
                  // context.fillStyle = "#fff";
                  //draw on entire canvas
                  //context.fillRect( 0, 0, canvas.width, canvas.height );
                   canvas.height = viewport.height;
                   canvas.width = viewport.width;

                    //imagez.src = canvas.toDataURL("image/png");
                   //
                   // Render PDF page into canvas context
                   //
                   //page.render({canvasContext: context, viewport: viewport});
                   var task = page.render({canvasContext: context, viewport: viewport})
              task.promise.then(function(){
                //console.log(canvas.toDataURL('image/png'));
                let imgItem = {imgref:canvas.toDataURL('image/png'),page:index+1,rotate:0}

                 let newState = that.state.imgsrc;
                 newState[index] = imgItem;
                 //let newState = that.state.imgsrc.concat(imgItem);
                that.setState({
                    imgsrc:newState
                });
                //imagez.src = canvas.toDataURL('image/png')
              });

             });
           });
       }

    pdfConversion = (urls)=>{
       /* this.props.dispatch({
            type: 'global/savePdfOrder',
            payload: urls
          });*/
          console.log('urls in pdf conversion : ',urls);
        if(window.PDFJS){
            console.log(this.state);
            //let urls = this.props.urls;
            for(var i = 0;i<urls.length;i++){
                let newurl = urls[i];
                //let newurl = 'http://172.104.60.70/st_old/uploads/defaultdocs/7/split/1527165241-42557/1_1527165241-42557.pdf';
                console.log('url : ',newurl);
               this.pdfLoop(newurl,i);
            }

            }
    }

    zoomPdf = (path)=>{
        console.log('path is : ',path);
        let url = path;
        this.setState({
            viewFileModal:true,
            pdfToZoom:url
        });
    }
    closeFileModal = ()=>{
        this.setState({
            viewFileModal:false
        });
    }

    deletePdf = (data,path,index,e)=>{
        console.log('item to delete : ',data);
        console.log('index is : ',index);
        console.log('pdfpath : ',path);
        let newImgSrc = this.state.imgsrc.slice();
        let newOrder = this.state.urlsOrder.slice();
        newOrder.splice(index,1);
        newImgSrc.splice(index,1);
        this.setState({
            imgsrc:newImgSrc,
            urlsOrder:newOrder
        });
        if(this.props.getUrlUpdate){
            this.props.getUrlUpdate(newOrder);
        }else if(this.props.getNewPdfOrder){
            this.props.getNewPdfOrder(newOrder);
        }
        /*
        if(this.props.getNewOrderEditPdf){
            this.props.getNewOrderEditPdf(newOrder);
        }

        this.props.dispatch({
            type: 'global/savePdfOrder',
            payload: newOrder
          });*/
        //also have to remove it from list which is sent to server on submit
        // or another option is to create a list of parts that i send back to server, just before sending
       /* let newUrls = [];
        this.state.urls.map((d)=>{
            if(d !== data){
                newUrls.push(d);
            }
        });
        this.setState({urls:newUrls},this.pdfConversion());
        */
    }


    rotatePdf = (item,index,path,e)=>{
        let newImgSrc = this.state.imgsrc;
        let rotate = '';
        if(newImgSrc[index].rotate<4){
            if((newImgSrc[index].rotate) ===3){
                newImgSrc[index].rotate = 0;
                rotate = 0;
            }else{
                newImgSrc[index].rotate = (newImgSrc[index].rotate)+1;
                rotate = 90*(newImgSrc[index].rotate)
            }
            this.setState({
                imgsrc:newImgSrc
            })

        }
        let urlsOrder = this.state.urlsOrder;
        let newItem = urlsOrder[index].replace('http://172.104.60.70/st_old/uploads/','');
        let file = urlsOrder[index].replace('http://172.104.60.70/st_old/uploads/','').split('/')[3];
        let num = file.split('_')[0];
        let toReplace = '/'+file;
        let filepath = '/'+ newItem.replace(toReplace,'');
        console.log('pdfpath : ',path);

        e.stopPropagation();
        console.log('item data : ',item);
        let url = devUrl + 'trip/retate_pdf/';
        console.log('url is : ',url);
        var formData = new FormData();
        formData.append('filename',this.props.item.name);
        formData.append('filepath',filepath);
        formData.append('angle',rotate);
       // filepath: /tripdoc/split/1528194456-85458
       //angle: 90
       //filename: 2_1527752445-64749.pdf
       postRequest(url,formData, null,response=>{
        console.log('response in data : ',response);

      },error=>console.log(error));    
        // var that = this;
        // fetch(url,{
        //     method: "post" ,
        //     credentials:'include',
        //     body:formData
        //   }).then((response)=>{
        //       return response.json();
        //   }).then((data)=>{
        //       return data;
        //   }).catch((err)=>console.log(err));

    }

    reorderArray = (oldIndex,newIndex,array)=>{
        let elementMoved = array[oldIndex];
        array[oldIndex]=array[newIndex];
        array[newIndex]=elementMoved;
        return array;
    }

    reOrder = (oldIndex,newIndex)=>{
        let newImgSrc = this.state.imgsrc;
        let newOrder = this.state.urlsOrder;
        console.log('array before sorting : ',newOrder)
       newImgSrc= this.reorderArray(oldIndex,newIndex,newImgSrc);
       newOrder = this.reorderArray(oldIndex,newIndex,newOrder)
       console.log('array after sorting : ',newOrder);
       if(this.props.getNewPdfOrder){
           this.props.getNewPdfOrder(newOrder);
       }
       /*
       if(this.props.getNewOrderEditPdf){
           this.props.getNewOrderEditPdf(newOrder);
       }

       this.props.dispatch({
        type: 'global/savePdfOrder',
        payload: newOrder
      });*/
       this.setState({
           imgsrc:newImgSrc,
           urlsOrder:newOrder
       });
    }

    updateCategory = (value) =>{
        this.setState({
        categorySelected:value
        });
    }

    render(){
        let num = this.props.num;
        let canvasDiv = [];
        let imgsDiv = [];
        if(this.state.imgsrc.length>0){
            this.state.imgsrc.map((item,index)=>{
              //let imgz =  <img key={index} src={item.imgref} alt="pdfimg"/>;
              let pdfpath = this.state.urlsOrder[index];
              //let pdfIndex = pdfpath.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split/','').split('/')[1].split('_')[0];
              let pdfIndex = item.page;
              let rotate = '';
              let rotateStyle = null;
              if(item.rotate){
                  rotate = 90*(item.rotate);
                  rotateStyle = {transform:`rotate(${rotate}deg)`};

              }
              //"http://172.104.60.70/st_old/uploads/clientsdoc/split/1529916893-26743/1_1529916878-36442.pdf"
              let imgz = (<div> <div className={styles.pdfButtons} >
                <span>Page No. {pdfIndex}</span>
                 <span className={styles.actIcons}>
                 <Icon onClick={(e)=>this.rotatePdf(item,index,pdfpath,e)} type="reload" /> <Icon onClick={(e)=>this.deletePdf(item,pdfpath,index,e)} type="close-circle-o" />
                 </span> 
                   </div>
                <img className={styles.imgThumb}  style={rotateStyle} src={item.imgref} key={index+100}  alt = "pdfimage"/><br/>
                <span className={styles.zoom} ><Icon onClick={()=>this.zoomPdf(pdfpath)} type="search" /> </span>
               </div>)
              imgsDiv.push(imgz);
            });
        }
        this.props.urls.map((item,index)=>{
            let canv =  <canvas key={index} style={{display:'none'}} ref={(ref) => this.canvasRefs[`canvas${index}`] = ref} > </canvas>;
            canvasDiv.push(canv);

        });

        return(
            <div>
            {canvasDiv.length>0?canvasDiv:''}
            {imgsDiv.length>0 && !this.props.showEditForm &&!this.props.showEmailUploadForm ?  <SortableComp reOrder={this.reOrder} hideLoading={this.props.hideLoading} imgsDiv={imgsDiv}  />  :''}
        {this.props.type && this.props.type==='addDoc'? '' : <div>{this.props.type==='maildoc' &&this.props.whichTab==='itinerary'?
          this.props.showEditForm ||this.props.type === 'maildoc' && this.props.showEmailUploadForm ?  <TripsForm 
            getUpdatedData={this.props.getUpdatedData}
            airlinesCategories={this.props.airlinesCategories}
            updateAirlineCat={this.updateAirlineCat}
            selectedAirlineCat = {this.state.selectedAirlineCat}
            updateSelectedCategory={this.updateCategory} 
            categorySelected={this.state.categorySelected} 
            whichTab={this.props.whichTab}
            // getUpdatedData={this.props.getUpdatedData} 
            closeModal={this.props.closeModal} 
            pdfOrder={this.state.urlsOrder} 
            // onSave={this.onSave} 
             categories={this.props.categories}
             type={this.props.type}
             tripid={this.props.tripid}
            // item={this.props.item}
            />:''
        :this.props.showEditForm && !this.props.uploadEmailDoc || this.props.showEmailUploadForm && this.props.uploadEmailDoc?<SaveEditedFiles
         getUpdatedData = {this.props.getUpdatedData}
         tripid={this.props.tripid}
         whichTab={this.props.whichTab}
        //  impCategories={this.props.impCategories}
         guidesCategories={this.props.guidesCategories}
         librarycategories={this.props.librarycategories}
         getClientDocs = {this.props.getClientDocs?this.props.getClientDocs:''} //from getclientdocs - 
         showSuccessMessage={this.props.showSuccessMessage} //from view client docs
         closeModal={this.props.closeModal}  // editpdf function from view client docs
         hideSplitFiles={this.props.hideSplitFiles}  //from editpdfmodal
         clientid={this.props.clientid}
         type={this.props.type}  // from addclientdocmodal which is getting it from the card we click on
          item={this.props.item}  // it is itemToedit - getting from viewclientdocs
           urlsOrder={this.state.urlsOrder}  //was getting from editpdfmodal but now will get from canvasrender
           categories={this.props.categories} 
           clientCategories={this.props.clientCategories}
           impCategories={this.props.impCategories}  // was getting from editpdfmodal and will still get it from there but pass through a number of components
            />:''}<br/></div>}
            {this.state.viewFileModal?<ViewPdfModal viewFileModal={this.state.viewFileModal} closeModal={this.closeFileModal} filepath={this.state.pdfToZoom}  />:''   }              

            </div>
        )
    }
}
2
Maybe it’s the same at beginning! Try to see what’s inside - mcssym
I have seen the property I wanted to compare with and it shows the updated values. - faraz
Can we see how/where/when you are setting state? - rockingskier
updated to show full code for the component. please take a look - faraz

2 Answers

0
votes

You can heavily shorten all this.props and this.state:

     getUpdatedData = {this.props.getUpdatedData}
     tripid={this.props.tripid}
     whichTab={this.props.whichTab}

into

     const {getUpdatedData, tripid, whichTab} = this.props

Are you sure length should be different? You have many setState() calls - it can be modified earlier. Show entire log from 'canvas mounted'.

0
votes

componentDidUpdate will work as it is. Check this demo on componentDidUpdate.

Demo

I guess, problem lies in somewhere between your component (state or props) while setState.

Can you expose your code base or make a demo with minimal code,that would be help. for ref, check this: prevState in componentDidUpdate is the currentState?