React Native updating data onState variable change - reactjs

i am trying to execute a function that update the Users data whenever the user come at the end of the Array like so :
componentDidUpdate = () => {
if (this.state.isLoading == false && this.state.Users.length == this.state.currentIndex) {
this.loadUsers()
}
}
Here is the loadUsers() function
loadUsers = () => {
Users = [
]
var query = firebase.database().ref("users").orderByKey();
query.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
getFilmDetailFromApi(childData.filmID).then(data => {
km = this.getDistance(this.state.userData.latitude, this.state.userData.longitude, childData.latitude, childData.longitude)
photo0 = null;
photo1 = null;
photo2 = null;
photo3 = null;
photo4 = null;
photo5 = null;
if(childData.photo[0]) {
photo0 = {uri: childData.photo[0]}
}
if(childData.photo[1]) {
photo1 = {uri: childData.photo[1]}
}
if(childData.photo[2]) {
photo2 = {uri: childData.photo[2]}
}
if(childData.photo[3]) {
photo3 = {uri: childData.photo[3]}
}
if(childData.photo[4]) {
photo4 = {uri: childData.photo[4]}
}
if(childData.photo[5]) {
photo5 = {uri: childData.photo[5]}
}
var filmImage = data.poster_path
Users.push({ id: key, uri: photo0, uri1: photo1, uri2: photo2, uri3: photo3, uri4: photo4, uri5: photo5, nom: childData.name, age:childData.age, film: filmImage, description: childData.description, distance: km })
this.setState({ users: key });
})
this.setState({Users: Users});
});
this.setState({isLoading: false});
this.setState({currentIndex: 0});
});
}
This work like the tinder cards, when i swipe them all (this.state.Users.length == this.state.currentIndex) become true and it render the loading screen and from there i want to re-run the loadUsers function to get new users but when i run the app i get : "Maximum update depth exceeded".

LoadUsers loads user and sets the state, which causes a rerender of loading screen. Then the loading screen run the LoadUser again trigers the flow again.
Edit1:
At least, you'd have to have some logic to update the status of loading:
Check the modified code:
loadUsers = () => {
Users = [
]
var query = firebase.database().ref("users").orderByKey();
query.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
this.setState({isLoading: true});
getFilmDetailFromApi(childData.filmID).then(data => {
km = this.getDistance(this.state.userData.latitude, this.state.userData.longitude, childData.latitude, childData.longitude)
photo0 = null;
photo1 = null;
photo2 = null;
photo3 = null;
photo4 = null;
photo5 = null;
if(childData.photo[0]) {
photo0 = {uri: childData.photo[0]}
}
if(childData.photo[1]) {
photo1 = {uri: childData.photo[1]}
}
if(childData.photo[2]) {
photo2 = {uri: childData.photo[2]}
}
if(childData.photo[3]) {
photo3 = {uri: childData.photo[3]}
}
if(childData.photo[4]) {
photo4 = {uri: childData.photo[4]}
}
if(childData.photo[5]) {
photo5 = {uri: childData.photo[5]}
}
var filmImage = data.poster_path
Users.push({ id: key, uri: photo0, uri1: photo1, uri2: photo2, uri3: photo3, uri4: photo4, uri5: photo5, nom: childData.name, age:childData.age, film: filmImage, description: childData.description, distance: km })
this.setState({ users: key, isLoading: false });
})
this.setState({Users: Users});});
this.setState({currentIndex: 0});
});
}

You are getting this error because you are trying to set state inside a loop and the maximum limit has reached to rerender a view once there is change in state. Try to set Users this.setState({ Users: Users }); once the foreach loop ends(outside of loop). this.setState({ users: key }); this may also need the similar approach.

Related

Data is dissapearing eventhough it is there at the same time

anybody know why the data exists in line 267 but not in 268? Any help is appreciated , thank you.
code
console
full function with useEffect watching props value to trigger the function
function createData() {
//loop through employees and create obj array
const emptyArray = [];
let counter = 0;
if (props.employees) {
const rowData = props.employees.map((item) => {
console.log(item.tests_taken);
let objectDetails = {
firstName: item.first_name,
lastName: item.last_name
};
console.log(item);
console.log(item.tests_taken[0]);
if (item.tests_taken[0]) {
console.log(item.tests_taken[0]);
item.tests_taken[0].forEach((test) => {
console.log(test[Object.keys(test)[0]]);
console.log('yo');
objectDetails = {
...objectDetails,
id: counter,
cefrLevel: test[Object.keys(test)[0]].overallScore.level,
cefrDescription:
test[Object.keys(test)[0]].overallScore.description,
overallScore: test[Object.keys(test)[0]].overallScore.score + '%',
assessmentDate: test[Object.keys(test)[0]].date
};
counter += 1;
emptyArray.push(objectDetails);
});
//console.log(emptyArray);
return objectDetails;
}
props.setEmployees(null);
});
setUsersArray(emptyArray);
console.log(usersArray);
return rowData;
}
}
useEffect(() => {
createData();
}, [props.employees]);

How to wait for .map() to finish and generate new keys in the array[index]

I'm trying to generate an array with values as follows:
{ name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array
with the initial values in the array as follow:
{ name: 'John', age: 35, employer: 'ABC' } //inital array
the function convertData() is handling all the array conversion.
async function convertData(data){
if(data.length === 0) return data;
// generates new array
const convertedDataArray = await data.map( async (row) =>{
let name = row.name
let paycheck = 0;
let last_paycheck = 0;
let change = 0;
const response = await axios.get('/getData', {params: {
name,
}});
let apiData = response.data.data;
if(apiData.length > 0){
let newData = apiData[0];
let oldData = apiData[1];
change = newData.payCheck - oldData.payCheck;
paycheck = newData.payCheck;
last_paycheck = oldData.payCheck;
}
console.log(apiData); // prints records up to 100 elements
return {...row, paycheck, last_paycheck, change };
});
console.log(convertedDataArray);// prints [Promise]
return Promise.all(convertedDataArray).then(() =>{
console.log(convertedDataArray); // prints [Promise]
return convertedDataArray;
});
};
where convertData() is called:
const response = await axios.get('/getEmployees',{params: {
token: id,
}});
const dataRows = response.data; //inital array
const tableRows = await convertData(dataRows);
return Promise.all(tableRows).then(() =>{
console.log(tableRows); // prints [Promise]
dispatch(setTableRows(tableRows));
});
I'm not sure why i keep getting Promise return I am still learning how to use promise correctly. Any help would be great, thank you in advance!
You should get a array of promises and use Promises.all to get all the data first.
Then use map() function to construct your data structure.
Example below:
async function convertData(data) {
try {
if (data.length === 0) return data;
const arrayOfPromises = data.map(row =>
axios.get("/getData", {
params: {
name: row.name,
},
})
);
const arrayOfData = await Promise.all(arrayOfPromises);
const convertedDataArray = arrayOfData.map((response, i) => {
const apiData = response.data.data;
let paycheck = 0;
let last_paycheck = 0;
let change = 0;
if (apiData.length > 0) {
const newData = apiData[0];
const oldData = apiData[1];
change = newData.payCheck - oldData.payCheck;
paycheck = newData.payCheck;
last_paycheck = oldData.payCheck;
}
return { ...data[i], paycheck, last_paycheck, change };
});
return convertedDataArray;
} catch (err) {
throw new Error(err);
}
}
(async function run() {
try {
const response = await axios.get("/getEmployees", {
params: {
token: id,
},
});
const dataRows = response.data;
const tableRows = await convertData(dataRows);
dispatch(setTableRows(tableRows));
} catch (err) {
console.log(err);
}
})();

How wait a "Array for each" function?

I got a little problem with synchronous/asynchronous system in the function "Array.foreach".
I don't know how to force my code to wait its end.
I tried to use await/async system but my code did not wait the code in "async responseDB =>".
This is my class:
...
let responsesDTO = [];
await Array.prototype.forEach.call(await searchResponsesByQuestionAndUserId(questions[cpt].idquestion, idUser), async responseDB => {
if(responseDB !== undefined){
const responseDTO = {
response_id:0,
response_text:"",
response_type:""
}
const responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text= responseEntity.text;
responseDTO.response_type= responseDB.type;
responsesDTO.push(responseDTO);
}
});
questionResponse.responses=responsesDTO;
questionResponses[cpt]=questionResponse;
}
Could you help me please? Thanks in advance.
I had to mock your async functions. However, the relevant part is to use for..of instead of forEach
async function searchResponsesByQuestionAndUserId() {
let responsesDB = [];
for (let i = 0; i < 10; i++) {
responsesDB.push({
response_id: parseInt(1000 * Math.random(), 10),
type: 'whatever ' + i
});
}
return new Promise((res) => {
window.setTimeout(() => {
res(responsesDB);
}, 1500);
});
}
async function searchResponseByResponseId(response_id) {
return new Promise((res) => {
window.setTimeout(() => {
res({
text: 'text for response ' + response_id
});
}, 300);
});
}
async function getResponsesDTO() {
let responsesDTO = [],
responsesDB = await searchResponsesByQuestionAndUserId();
for (let responseDB of responsesDB) {
if (responseDB === undefined) {
continue;
}
let responseDTO = {
response_id: 0,
response_text: "",
response_type: ""
},
responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text = responseEntity.text;
responseDTO.response_type = responseDB.type;
responsesDTO.push(responseDTO);
console.log({responseDTO});
}
return responsesDTO;
}
getResponsesDTO().then(responsesDTO => {
console.log(responsesDTO);
});

React TypeError: " this is undefined ", function inside function call not working

Trying to call addChildNodeNext method in addChildNode function, but
result = this.addChildNodeNext(item.childrens,CurrentID)
gives error of this is undefined. I have already bind both function in constructor.
class TestAdd extends Component {
constructor(props) {
super(props)
this.addChildNode = this.addChildNode.bind(this)
this.addChildNodeNext = this.addChildNodeNext.bind(this)
}
addChildNodeNext = (nodeList, CurrentID) => {
alert(`Self ${nodeList} : ${CurrentID}`)
return nodeList
}
addChildNode = (nodeList, CurrentID) => {
const { childIndex } = this.state
let index = childIndex
const newTree = nodeList.filter(function (item) {
alert(`Self ${item.name} : ${CurrentID}`)
index += 1
let result = ""
if (item.name === CurrentID) {
const newName = `child_${childIndex}_${CurrentID}`
result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
} else if (item.childrens.length > 0) {
result = this.addChildNodeNext(item.childrens, CurrentID)
} else {
result = item
}
return result
});
this.setState({ childIndex: index })
this.setState({ treeNode: newTree })
}
}
export default TestAdd;
You are using a regular function in your .filter method. This is why you lose this context there. Also, you don't need to bind your functions in the constructor because you are using arrow functions.
addChildNode = (nodeList, CurrentID) => {
const { childIndex } = this.state
let index = childIndex
const newTree = nodeList.filter(function (item) { // <--- HERE
alert(`Self ${item.name} : ${CurrentID}`)
index += 1
let result = ""
if (item.name === CurrentID) {
const newName = `child_${childIndex}_${CurrentID}`
result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
} else if (item.childrens.length > 0) {
result = this.addChildNodeNext(item.childrens, CurrentID)
} else {
result = item
}
return result
});
this.setState({ childIndex: index })
this.setState({ treeNode: newTree })
}
You can replace it with an arrow function:
addChildNode = (nodeList, CurrentID) => {
const { childIndex } = this.state
let index = childIndex
const newTree = nodeList.filter(item => {
alert(`Self ${item.name} : ${CurrentID}`)
index += 1
let result = ""
if (item.name === CurrentID) {
const newName = `child_${childIndex}_${CurrentID}`
result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
} else if (item.childrens.length > 0) {
result = this.addChildNodeNext(item.childrens, CurrentID)
} else {
result = item
}
return result
});
this.setState({ childIndex: index })
this.setState({ treeNode: newTree })
}

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