I have following problem, which I don't know how to properly tackle.
I have "list" of all purchased images on my view. I display them with v-for loop. Each image also has progress-bar element, so when user clicks on download button, downloadContent function gets executed and progress bar should be displayed.
So my html looks like this.
<section class="stripe">
<div class="stripe__item card" v-for="(i, index) in purchasedImages">
<progress-bar :val="i.download_progress"
v-if="i.download_progress > 0 && i.download_progress < 100"></progress-bar>
<div class="card__wrapper">
<img :src="'/'+i.thumb_path" class="card__img">
</div>
<div class="btn-img card__btn card__btn--left" #click="downloadContent(i.id_thumb, 'IMAGE', index)">
</div>
</div>
</section>
And this is my JS Code
import Vue from 'vue'
import orderService from '../api-services/order.service';
import downloadJs from 'downloadjs';
import ProgressBar from 'vue-simple-progress';
export default {
name: "MyLocations",
components: {
ProgressBar: ProgressBar
},
data() {
return {
purchasedImages: {},
purchasedImagesVisible: false,
}
},
methods: {
getUserPurchasedContent() {
orderService.getPurchasedContent()
.then((response) => {
if (response.status === 200) {
let data = response.data;
this.purchasedImages = data.images;
if (this.purchasedImages.length > 0) {
this.purchasedImagesVisible = true;
// Set download progress property
let self = this;
this.purchasedImages.forEach(function (value, key) {
self.purchasedImages[key].download_progress = 0;
});
}
}
})
},
downloadContent(id, type, index) {
let self = this;
orderService.downloadContent(id, type)
.then((response) => {
let download = downloadJs(response.data.link);
download.onprogress = function (e) {
if (e.lengthComputable) {
let percent = e.loaded / e.total * 100;
let percentage = Math.round(percent);
if (type === 'IMAGE') {
// Is this proper way to set one field reactive?
self.purchasedImages[index].download_progress = percentage;
if (percentage === 100) {
self.purchasedImages[index].download_progress = 0;
}
}
}
}
})
},
},
mounted: function () {
this.getUserPurchasedContent();
}
};
So the problem is. When user clicks on download button, download starts to execute and I get downloaded content, but I don't see progress bar. So I wonder, is this a proper way to set element reactive? How should my implementation look like? How to properly set self.purchasedImages[index].download_progress object key value, so progress bar will be visible?
If you need any additional informations, please let me know and I will provide. Thank you!
The snippet:
this.purchasedImages = data.images;
Leads us to believe data.images is an array of objects that do not have the download_progress property. So Vue can't detect/react when it changes.
To fix that, you can use Vue.set:
Vue.set(self.purchasedImages[key], 'download_progress', 0);
This is very well explained in Vue.js docs.
Another option: add the property before assigning to data
Just for completeness, you could also add the download_progress before assigning the array to the data property. This would allow Vue to notice it and be able to react to it.
Example:
let data = response.data;
this.purchasedImages = data.images.map(i => ({...i, download_progress: 0}));
if (this.purchasedImages.length > 0) {
this.purchasedImagesVisible = true;
// no need to set download_progress here as it was already set above
}
// if above could also be simplified to just:
this.purchasedImagesVisible = this.purchasedImages.length;
On a side note, since it is gonna be an array and not an object, I suggest you declare it as such:
data() {
return {
purchasedImages: [], // was: {},
This will have no effect, since you overwrite purchasedImages completely in (this.purchasedImages = data.images;), but it is a good practice as it documents that property's type.
Related
So I have a webpage that's meant to model a sort of questionnaire. Each question would take up the whole page, and the user would switch back and forth between questions using the arrow keys. That part's fine, swapping components on button pressing doesn't seem to be an issue, and I got a proof-of-concept of that working before.
The trouble is, these questionnaires won't have the same number of questions every time. That'll depend on the choice of the person making the questionnaire. So I stored the number of questions in a variable held in the Django Model, and I fetch that variable and try to generate x number of components based on that integer. At the moment I'm just trying to get it to generate the right number of components and let me navigate between them properly, I'll worry about filling them with the proper content later, because I'm already having enough trouble with just this. So here's my code:
import React, { useState, useEffect, cloneElement } from 'react';
import { useParams } from 'react-router-dom'
import QuestionTest from './questiontest';
function showNextStage(displayedTable, questionCount) {
let newStage = displayedTable + 1;
if (newStage > questionCount) {
newStage = questionCount;
}
return newStage;
}
function showPreviousStage(displayedTable) {
let newStage = displayedTable - 1;
if (newStage < 1) {
newStage = 1;
}
return newStage;
}
export default function Questionnaire(props) {
const initialState = {
questionCount: 2,
is_host: false
}
const [ roomData, setRoomData ] = useState(initialState)
const { roomCode } = useParams()
useEffect(() => {
fetch("/audio/get-room" + "?code=" + roomCode)
.then(res => res.json())
.then(data => {
setRoomData({
roomData,
questionCount: data.questionCount,
isHost: data.isHost,
})
})
},[roomCode,setRoomData])
const [ displayedTable, setDisplayedTable ] = useState(1);
let initialComponents = {};
for (let i = 1; i < roomData.questionCount + 1; i++) {
initialComponents[i] = <div><p>{i}</p> <QuestionTest /></div>
}
// "<QuestionTest />" is just a random component I made and "{i}" is
// to see if I'm on the right one as I test.
const [components] = useState(initialComponents);
useEffect(() => {
window.addEventListener('keydown', (e) => {
if (e.keyCode == '39') {
setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
} else if (e.keyCode == '37') {
setDisplayedTable(showPreviousStage(displayedTable));
}
});
return () => {
window.removeEventListener('keydown', (e) => {
if (e.keyCode == '39') {
setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
} else if (e.keyCode == '37') {
setDisplayedTable(showPreviousStage(displayedTable));
}
});
};
}, []);
return (
<div>
{components[displayedTable]}
</div>
)
}
So the trouble with this is, I need to set an initial state for the questionCount variable, or else I get errors. But this initial state is replaced almost immediately with the value set for this questionnaire, as retrieved by the fetch function, and so the state resets. The initial questionCount value of 2 however gets used in the component generation and in the adding of the eventListeners, and so when the page is generated it just has two components rather than a number matching questionCount's value for the questionnaire.
I don't really understand this tbh. If I remove the window.addEventLister from useEffect and make it standalone, then it works and the right number of components are generated, but then it adds a new EventListener every time the state refreshes, which starts to cause immense lag as you switch back and forth between pages as the function calls pile up and up.
So I don't really know how to achieve this. My entire way of going about this from the onset is probably terribly wrong (I just included it to show I made an attempt and wasn't just asking for it to be done for me), but I can't find any examples of what I'm trying to do online.
My parent component takes input from a form and the state changes when the value goes out of focus via onBlur.
useEffect(() => {
let duplicate = false;
const findHierarchy = () => {
duplicationSearchParam
.filter(
(object, index) =>
index ===
duplicationSearchParam.findIndex(
(obj) => JSON.stringify(obj.name) === JSON.stringify(object.name)
)
)
.map((element) => {
DuplicateChecker(element.name).then((data) => {
if (data.status > 200) {
element.hierarchy = [];
} else {
element.hierarchy = data;
}
});
if (duplicate) {
} else {
duplicate = element?.hierarchy?.length !== 0;
}
});
return duplicate;
};
let dupe = findHierarchy();
if (dupe) {
setConfirmationProps({
retrievedData: formData,
duplicate: true,
responseHierarchy: [...duplicationSearchParam],
});
} else {
setConfirmationProps({
retrievedData: formData,
duplicate: false,
responseHierarchy: [],
});
}
}, [duplicationSearchParam]);
I have a child component also uses a useeffect hook to check for any state changes of the confirmationProps prop.
the issue is that the event gets triggered onblur, and if the user clicks on the next button. this function gets processes
const next = (data) => {
if (inProgress === true) {
return;
}
inProgress = true;
let countryLabels = [];
formData.addresses?.map((address) => {
fetch(`/api/ref/country/${address?.country}`)
.then((data) => {
countryLabels.push(data.label);
return countryLabels;
})
.then((countries) => {
let clean = MapCleanse(data, countries);
fetch("/api/v1/organization/cleanse", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(clean),
})
.then((data) => {
if (data.status > 200) {
console.log(data.message);
message.error(getErrorCode(data.message.toString()));
} else {
Promise.all([confirmationProps, duplicationSearchParam]).then(
(values) => {
console.log(values);
console.log(data);
setCleansed(data);
**setCurrent(current + 1);**
inProgress = false;
}
);
}
})
.catch((err) => {
console.log(err);
inProgress = false;
});
})
.catch((err) => {
console.log(err);
inProgress = false;
});
});
console.log(confirmationProps);
};
The important part in the above code snippet is the setCurrent(current + 1) as this is what directs our code to render the child component
in the child component, i have a use effect hook that is watching [props.duplicateData.responseHierarchy]
I do output the values of props.duplicateData.responsehierarchy to the console to see if the updated information gets passed to the child component and it does. the values are present.
I have a conditional render statement that looks like this
{cleansedTree?.length > 0 || treeDuplicate ? (...)}
so although the data is present and is processed and massaged in the child component. it still will not re render or display properly. unless the user goes back to the previous screen and proceeds to the next screen again... which forces a re-render of the child component.
I have boiled it down and am assuming that the conditional rendering of the HTML is to blame. Or maybe when the promise resolves and the state gets set for the confirmation props that the data somehow gets lost or the useefect doesn't pick it up.
I have tried the useefect dependency array to contain the props object itself and other properties that arent directly related
UPDATE: this is a code snippet of the processing that gets done in the childs useeffect
useEffect(() => {
console.log(props.duplicate);
console.log(props.duplicateData);
console.log(props.confirmationProps);
let newArray = props.duplicateData.filter((value) => value);
let duplicateCheck = newArray.map((checker) =>
checker?.hierarchy?.find((Qstring) =>
Qstring?.highlightedId?.includes(UUIDToString(props?.rawEdit?.id))
)
);
duplicateCheck = duplicateCheck.filter((value) => value);
console.log(newArray, "new array");
console.log(duplicateCheck, "duplicate check");
if (newArray?.length > 0 && duplicateCheck?.length === 0) {
let list = [];
newArray.map((dupeData) => {
if (dupeData !== []) {
let clean = dupeData.hierarchy?.filter(
(hierarchy) => !hierarchy.queryString
);
let queryParam = dupeData.hierarchy?.filter(
(hierarchy) => hierarchy.queryString
);
setSelectedKeys([queryParam?.[0]?.highlightedId]);
let treeNode = {};
if (clean?.length > 0) {
console.log("clean", clean);
Object.keys(clean).map(function (key) {
treeNode = buildDuplicate(clean[key]);
list.push(treeNode);
return list;
});
setCleansedTree([...list]);
setTreeDuplicate(true);
} else {
setTreeDuplicate(false);
}
}
});
}
}, [props.duplicateData.responseHierarchy]);
This is a decently complex bit of code to noodle through, but you did say that **setCurrent(current + 1);** is quite important. This pattern isn't effectively handling state the way you think it is...
setCurrent(prevCurrent => prevCurrent + 1)
if you did this
(count === 3)
setCount(count + 1) 4
setCount(count + 1) 4
setCount(count + 1) 4
You'd think you'd be manipulating count 3 times, but you wouldn't.
Not saying this is your answer, but this is a quick test to see if anything changes.
The issue with this problem was that the state was getting set before the promise was resolved. to solve this issue I added a promise.all function inside of my map and then proceeded to set the state.
What was confusing me was that in the console it was displaying the data as it should. but in fact, as I learned, the console isn't as reliable as you think. if someone runs into a similar issue make sure to console the object by getting the keys. this will return the true state of the object, and solve a lot of headache
Currently i'm doing a quiz composed by multiple categories that can be chosen by the user and i wanna check if the user responded to all questions. For doing that, i compared the number of questions he answered with the number of questions gived by the api response. The problem is that i have an "submit answers" button at the end of the last question, with that onClick function:
const sendAnswers = (e, currentQuiz) => {
setQuizzes({...quizzes, [currentQuiz]:answers});
setAnswers([])
var answeredToAllQuestions = true
DataState.map(function (quiz) {
if(quiz.category in quizzes){
if(Object.keys(quiz.questions).length !== Object.keys(quizzes[quiz.category]).length){
answeredToAllQuestions=false;
}
}
});
if(answeredToAllQuestions === false){
setAlertTrigger(1);
}
else{
setNumber(number+1);
}
}
in that function i use setState on this line: setQuizzes({...quizzes, [currentQuiz]:answers}); to upload the answers he checked on the last question before checking if he answered to all questions. The problem is that state of quizzes is not updated imediatly and it s not seen by the if condition.
I really don't know how am i supposed to update the state right after setting it because, as i know, react useState updates the state at the next re-render and that causes trouble to me..
Considering that quizzes will be equal to {...quizzes, [currentQuiz]:answers} (after setQuizzes will set it), there is no reason to use quizzes in if condition. Replace it with a local var and problem will be solved.
const sendAnswers = (e, currentQuiz) => {
let futureValueOfQuizzes = {...quizzes, [currentQuiz]:answers}
setQuizzes(futureValueOfQuizzes);
setAnswers([])
var answeredToAllQuestions = true
DataState.map(function (quiz) {
if(quiz.category in futureValueOfQuizzes){
if(Object.keys(quiz.questions).length !== Object.keys(quizzes[quiz.category]).length){
answeredToAllQuestions=false;
}
}
});
if(answeredToAllQuestions === false){
setAlertTrigger(1);
}
else{
setNumber(number+1);
}
}
I would like to take this opportunity to say that these type of problems appear when you use React state for your BI logic. Don't do that! Much better use a local var defined in components body:
const Component = () => {
const [myVar , setMyVar] = useState();
let myVar = 0;
...
}
If myVar is used only for BI logic, use the second initialization, never the first!
Of course sometimes you need a var that is in BI logic and in render (so the state is the only way). In that case set the state properly but for script logic use a local var.
You have to either combine the useState hook with the useEffect or update your sendAnswers method to perform your control flow through an intermediary variable:
Using a temporary variable where next state is stored:
const sendAnswers = (e, currentQuiz) => {
const newQuizzes = {...quizzes, [currentQuiz]:answers};
let answeredToAllQuestions = true
DataState.map(function (quiz) {
if(quiz.category in newQuizzes){
if (Object.keys(quiz.questions).length !== Object.keys(newQuizzes[quiz.category]).length){
answeredToAllQuestions = false;
}
}
});
setQuizzes(newQuizzes);
setAnswers([]);
if (answeredToAllQuestions === false) {
setAlertTrigger(1);
} else {
setNumber(number+1);
}
}
Using the useEffect hook:
const sendAnswers = (e, currentQuiz) => {
setQuizzes({...quizzes, [currentQuiz]:answers});
setAnswers([]);
}
useEffect(() => {
let answeredToAllQuestions = true
DataState.map(function (quiz) {
if(quiz.category in quizzes){
if (Object.keys(quiz.questions).length !== Object.keys(quizzes[quiz.category]).length){
answeredToAllQuestions = false;
}
}
});
if (answeredToAllQuestions === false) {
setAlertTrigger(1);
} else {
setNumber(number+1);
}
}, [quizzes]);
Creating my first ReactJS Website and using Node in the back-end, currently in the code that follows I fetch data that I then print on the page. I manage to print the names of the people in a project, their picture and their email from the server BUT the description of the project i get the error :
TypeError: Cannot read property '0' of undefined
Which I do not understand.
Here is the code :
class ProjectPage extends Component {
constructor(props) {
super(props);
this.state = {
user: [],
description: [],
mail: [],
name: [],
};
this.getNames = this.getNames.bind(this);
this.getPictures = this.getPictures.bind(this);
this.getMails = this.getMails.bind(this);
this.getDetails = this.getDetails.bind(this);
}
I create the class and all the elements that are required
componentDidMount() {
console.log("BEGIN componentDidMount");
this.fetchDetails();
this.fetchNames();
this.fetchMails();
console.log("END componentDidMount");
}
Call all the function in my componentDidMount()
fetchDetails() {
console.log("BEGIN fetchDetails()");
let url = 'http://192.168.1.33:8080/getprojectdetails/Aprite';
console.log("url details = " + url);
fetch(url)
.then(results => {
var json = results.json();
return json;
})
.then(data => {
this.setState({ description: data });
})
console.log("END fetchData()");
}
Here is the fetch of the project description
getDetails = () => {
let lines = [];
let nbr = this.state.description.length;
console.log("nbr = " + nbr);
if (nbr){
console.log("lines = " + this.state.description[0].P_Description);
for (let i = 0; i < nbr; i++)
lines.push(<div key={this.state.descripton[i].P_Description}></div>);
}
return (lines);
}
And the function to print the data in the Render() function
But when i try to print this data, the value of nbr passes from 0 to 1 then to 0 again... in the console log I can see the description but it doesn't appear on the website and I don't get it.
Please help me ?
There is a typo in the inner loop inside the getDetails function
You should write this.state.description not this.state.descripton
Hope this solves your problem :)
So with the React render lifecycle system, the componentDidMount will actually happen after the first render. During that first render, you're trying to access the first element of an empty array, which is the error you are seeing.
In order to solve this problem, in your render method, you should have a fallback something to render while we wait for the fetchDetails to return a value from the server. If you want it to render nothing, you can just return null.
ie.
const { description = [] } = this.state;
if (description.length === 0) {
return null;
}
return this.getDetails();
As a side note, in order to avoid having all of those (which gets pretty unmaintainable):
this.getNames = this.getNames.bind(this);
this.getPictures = this.getPictures.bind(this);
this.getMails = this.getMails.bind(this);
this.getDetails = this.getDetails.bind(this);
You can just define them as class properties like so:
getNames = () => {
// do stuff
}
I have a filter to convert content with id into user name. For instance, it converts Thank you #id-3124324 ! into Thank you #Jack !.
var filter = function (content) {
var re = /\s#(id\-\d+)\s/g;
var matches = [];
var lastMatch = re.exec(content);
while (lastMatch !== null) {
matches.push(lastMatch[1]); // uid being mentioned
lastMatch = re.exec(content);
}
// TODO: query user name from matched id
// replace id with user name
// fake usernames here
var usernames = ['Random Name'];
for (var i = 0; i < usernames.length; ++i) {
content = content.replace(new RegExp(matches[i], 'g'), usernames[i]);
}
return content;
};
Vue.filter('username', filter);
But in my case, usernames should be achieved with AJAX of a query with id. How should I do it?
Anything you can do with a filter you can do with a computed. In Vue 2.0, there won't be filters, so you'll need to use computeds instead.
Fetching data asynchronously into a computed is a somewhat messy problem, which is why there is the vue-async-computed plugin. The difficulty is that the computed has to return a value synchronously, when it hasn't finished fetching data.
The solution is to have the computed depend on a cache of fetched data. If the needed value isn't in the cache, the computed kicks off the async process to fetch it and returns some placeholder value. When the process adds a value to the cache, the computed should notice the change in the cache and return the complete value.
In the demo below, I had to make an auxiliary variable, trigger, which I reference in the computed just so I know there's been an update. The fetch process increments trigger, which triggers the computed to re-evaluate. The computed doesn't notice when values are added to or updated in decodedIds. There may be a better way to deal with that. (Using async computed should make it a non-issue.)
vm = new Vue({
el: 'body',
data: {
messages: [
'Thank you #id-3124324!'
],
decodedIds: {},
trigger: 0
},
computed: {
decodedMessages: function() {
return this.messages.map((m) => this.decode(m, this.trigger));
}
},
methods: {
decode: function(msg) {
var re = /#(id\-\d+)/g;
var matches = msg.match(re);
for (const i in matches) {
const p1 = matches[i].substr(1);
if (!(p1 in this.decodedIds)) {
// Indicate name is loading
this.decodedIds[p1] = '(...)';
// Mock up fetching data
setTimeout(() => {
this.decodedIds[p1] = 'some name';
++this.trigger;
}, 500);
}
}
return msg.replace(re, (m, p1) => this.decodedIds[p1]);
}
}
});
setTimeout(() => {
vm.messages.push('Added #id-12345 and #id-54321.');
}, 1500);
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div v-for="message in decodedMessages">
{{message}}
</div>