How to display the React Axios progress bar? - reactjs

I want the result screen
My componentDidMount ()
_isMounted = false;
componentDidMount() {
this._isMounted = true;
var page = 0; // 공정 라인 수
//비가동 현황 불러오기
let oprationStatus = () => {
axios.get('http://localhost:8080/api/process/FM')
.then(response => {
var output = response && response.data;
//비가동 현황
NonOperationalStatus.data.series[0][0] = output.list[page].nop_000; // 계획
NonOperationalStatus.data.series[0][1] = output.list[page].nop_001; // 재료
NonOperationalStatus.data.series[0][2] = output.list[page].nop_002; // 금형
NonOperationalStatus.data.series[0][3] = output.list[page].nop_003; // 설비
NonOperationalStatus.data.series[0][4] = output.list[page].nop_004; // 사람
NonOperationalStatus.data.series[0][5] = output.list[page].nop_etc; // 기타
});
}
//가동율 등등 기본 정보 가져오기
let getProcess = () => {
oprationStatus();
axios.get('http://localhost:8080/api/process/FM')
.then(response => {
var output = response && response.data;
if(this._isMounted) {
this.setState({
data: output.list[page]
})
if(page < output.list.length-1) {
page++;
} else if(page == output.list.length-1) {
page = 0;
this.props.history.push('/hdprocess')
}
setTimeout(getProcess, 1000 * 5); // 매 5초마다 값 가져옴
}
});
}
getProcess();
}
componentWillUnmount() {
this._isMounted = false;
}
This code gets the data from the API server at 5 second intervals and routes it to the next page.
What I want is to display a progress icon as the picture above while the asynchronous communication is loading.
Let me know if you have a good alternative

Initially use a progress or spinner component.
Use it until a valid Response is return from the Axios Function, if a valid Response is attained, change the spinner(progres bar) Component to the actual component

Related

filter the listed items according to their Categories in Reactjs

i have been suffering to get the items' data listed according to their categories
i don't know what am I doing wrong.
so basically, I have data coming from a bearer token API and it is listed successfully on the screen but I want as a second step to list according to their categories. there are five categories and more than 60 items.
here is my code:
const [filterList, setFilterList] = useState("all");
const [newProduct, setNewProduct] = useState(products);
// filtering data by category
useEffect(() => {
let isValidScope = true;
const fetchData = async () => {
// pass filterList in fetch to get products for the selected category ??
// pass parameters to fetch accordingly
const res = await fetch(
"https://myapi-api.herokuapp.com/api/categories/",
{
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
if (!isValidScope) {
return;
}
setNewProduct(res);
};
fetchData();
return () => {
isValidScope = false;
};
}, [filterList]);
function onFilterValueSelected(filterValue) {
setFilterList(filterValue);
}
let filteredProductList = newProduct?.filter((product) => {
// should return true or false
// option 2 if product has a category property
return product.category === filterList;
// existing code
if (filterList === "electronics") {
return product.electronics == true;
} else if (filterList === "clothing") {
return product.clothing === true;
} else if (filterList === "accsessories") {
return product.accsessories === true;
} else if (filterList === "furniture") {
return product.furniture === true;
} else if (filterList === "hobby") {
return product.hobby === true;
} else {
// here dont return truthy
return false;
}
});
You could fetch all of them once when the component mounts and them filter them on every render based on the selected filter instead of fetching products everytime in useEffect when filter changes.
const [filterCategory, setFilterCategory] = useState("");
function onFilterValueSelected(filterValue) {
setFilterCategory(filterValue);
}
let filteredProductList = newProduct?.filter((product) => {
return product.category === filterCategory;
});
Try something like that:
const categories = ['Cat1', 'Cat2', 'Cat3'] // Since you hardcode it anyway, its fine to have a hardcoded array here. But you can retrieve unique categories by getting Object.values on category and new Set() them
return (<> {categories.forEach(category => {
fetchedData.filter(el => el.category === category).map(filteredElement => {return <h1> {filteredElement.property} <h1>})}) </>}

Lifecycle of useState hook in React.js

I have the following synchronism problem. Given that I know that the React useState hook is asynchronous, I run into the following: I'm downloading some images from Amazon S3, I manage to save it correctly in my hook: defaultSelfiePicture and depending on the weight of the image (or so I think) sometimes I get the images loaded correctly and sometimes not. I have tried to force state changes after I finish saving the object in my hook but it never renders the image, only if I change component and come back is when it is shown in the cases that it takes longer to load.
const [defaultSelfiePictures, setDefaultSelfiePictures] = useState([])
useEffect(() => {
if (savedUser.docs !== undefined) {
loadAllPictures()
}
}, [savedUser.docs.length])
const loadAllPictures = () => {
let p1 = loadUrlDefaultFrontPictures()
let p2 = loadUrlDefaultBackPictures()
let p3 = loadUrlDefaultSelfiePictures()
Promise.all([p1, p2, p3]).then(result => {
console.log('end all promises')
setTimestamp(Date.now())
})
}
const loadUrlDefaultSelfiePictures = async () => {
if (savedUser.docs.length > 0) {
let readedPictures = []
for (let i = 0; i < savedUser.docs.length; i++) {
if (
savedUser.docs[i].type === 'SELFIE'
//&& savedUser.docs[i].side === 'FRONT'
) {
if (
savedUser.docs[i].s3Href !== null &&
savedUser.docs[i].s3Href !== undefined
) {
const paramsKeyArray =
savedUser.docs[i].s3Href.split('')
let paramsKey = paramsKeyArray.pop()
let params = {
Bucket: process.env.REACT_APP_S3_BUCKET,
Key: paramsKey
}
await s3.getSignedUrl('getObject', params, function (err, url) {
readedPictures.push({
idKycDoc: savedUser.docs[i].idKycDoc,
name: 'selfie.jpeg',
type: savedUser.docs[i].type,
url: url
})
})
} else {
let urlPicture = savedUser.docs[i].localHref
let response = await axios.get(`${URL_IMG}${urlPicture}`, {
responseType: 'blob'
})
function readAsDataURL(data) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(data)
reader.onloadend = () => {
resolve(reader.result)
}
})
}
const base64Data = await readAsDataURL(response.data)
readedPictures.push({
idKycDoc: savedUser.docs[i].idKycDoc,
name: 'selfie.jpeg',
type: savedUser.docs[i].type,
url: `data:image/jpeg;base64,${base64Data.slice(21)}`
})
}
}
}
setDefaultSelfiePictures(readedPictures)
}
}
And I obtain this :
I can see that the hook has content, but that content is not updated until the next rendering of the component, also if I try to make any changes when I detect that the .length has changed it tells me that it is 0...
And right after the next render I get this:

Not able to add chat message using Sockjs in react native

I am facing issue in adding chat message in my Flatlist because I am not able to call any function inside stompClient.subscribe ()
My code is as following :
dummy='dummyurl';
sock = new SockJS(this.dummy);
componentDidMount() {
var that = this;
this.sock.onConnect =(e) =>{
console.log("connected")
}
this.sock.onopen = function() {
console.log('open');
var dummy2='dummyurl';
var sock2 = new SockJS(dummy2);
let stompClient = Stomp.over(sock2);
stompClient.heartbeat.outgoing = 20000;
stompClient.heartbeat.incoming = 0;
stompClient.connect({}, (frame) => {
stompClient.subscribe('xyz/getChat', (messageOutput) =>{
var mymessage =JSON.parse(messageOutput.body).message;
this.state = {
incomingchatMessage: "",
chatMessages:[]
}
that.setState({incomingchatMessage:mymessage}) //getting issue setState not found
console.log(this.state)
});
});
};
this.sock.onmessage =(e) =>{
console.log('message', e);
alert("on message calledj")
};
this.sock.onmessage = evt => {
console.log("erve");
}
}
In this code I am able to get net message inside new_message variable but not able to update state value here .
Any solution of this condition .

Firebase upload multiple files and get status

I have a React form where the user can upload multiple files. These are stored in fileList
async function uploadFiles(id) {
try {
const meta = await storageUploadFile(fileList, id);
console.log(meta);
} catch (e) {
console.log(e);
}
}
This calls my helper function that uploads the files to Firebase
export const storageUploadFile = function(files, id) {
const user = firebase.auth().currentUser.uid;
return Promise.all(
files.map((file) => {
return storage.child(`designs/${user}/${id}/${file.name}`).put(file)
})
)
};
What I'd like is on calling uploadFiles, get the total filesize of all items, and then show the overall progress.
At the moment, my code is only returning the file status in an array on completion
[
{bytesTransferred: 485561, totalBytes: 485561, state: "success"},
{bytesTransferred: 656289, totalBytes: 656289, state: "success"}
]
This is the way i do it:
import Deferred from 'es6-deferred';
export const storageUploadFile = function(files, id) {
const user = firebase.auth().currentUser.uid;
// To track the remaining files
let itemsCount = files.length;
// To store our files refs
const thumbRef = [];
// Our main tasks
const tumbUploadTask = [];
// This will store our primses
const thumbCompleter = [];
for (let i = 0; i < files.length; i += 1) {
thumbRef[i] = storage.ref(`designs/${user}/${id}/${file.name}`);
tumbUploadTask[i] = thumbRef[i].put(files[i]);
thumbCompleter[i] = new Deferred();
tumbUploadTask[i].on('state_changed',
(snap) => {
// Here you can check the progress
console.log(i, (snap.bytesTransferred / snap.totalBytes) * 100);
},
(error) => {
thumbCompleter[i].reject(error);
}, () => {
const url = tumbUploadTask[i].snapshot.metadata.downloadURLs[0];
itemsCount -= 1;
console.log(`Items left: ${itemsCount}`)
thumbCompleter[i].resolve(url);
});
}
return Promise.all(thumbCompleter).then((urls) => {
// Here we can see our files urls
console.log(urls);
});
};
Hope it helps.

prevState showing updated state in componentDidUpdate

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>
)
}
}
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'.
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?

Resources