React - State not updating - javascript

When I click the button that triggers subscribe() I'm trying to change this.state.subscribe to be the opposite boolean of what it is. I'm not even managing change the value of this.state.subscribed much less render different text when clicking the button. I've tried replaceState and adding call back function. Not exactly sure what I should be putting in the call back function though, if that's what I'm doing wrong.
SingleSubRedditList = React.createClass({
mixins: [ReactMeteorData],
getMeteorData: function(){
Meteor.subscribe('posts');
var handle = Meteor.subscribe('profiles');
return {
loading: !handle.ready(),
posts: Posts.find().fetch(),
profiles: Profiles.find({}).fetch()
};
},
getInitialState: function(){
var subscribed;
return {
subscribed: subscribed
};
},
populateButton: function(){
//fetch is cumbersome, later try and do this another way to make it faster
var profile = Profiles.find({_id: Meteor.userId()}).fetch();
if (profile.length > 0){
this.state.subscribed = profile[0].subreddits.includes(this.props.subreddit);
}
},
subscribe: function(){
this.setState({
subscribed: ! this.state.subscribed
}
);
},
renderData: function(){
return this.data.posts.map((post) => {
return <SinglePost title={post.title} content={post.content} key={post._id} id={post._id} />
});
},
render: function(){
this.populateButton()
return (
<div>
<button onClick={this.subscribe}>
<p>{this.state.subscribed ? 'Subscribed' : 'Click To Subscribe'}</p>
</button>
<p></p>
<ul>
{this.renderData()}
</ul>
</div>
);
}
});

You can't set the state using this.state.subscribed = ..., which you are currently doing in populateButton. Trying to directly mutate the state like that will cause it to behave strangely.
You are also initializing subscribed with an undefined variable. You should give it an initial status of true or false.

Related

VueJS / JS DOM Watch / Observer in a multi phase render scenario

Scenario:
I’m developing a Vue scroll component that wraps around a dynamic number of HTML sections and then dynamically builds out vertical page navigation allowing the user to scroll or jump to page locations onScroll.
Detail:
a. In my example my scroll component wraps 3 sections. All section id’s start with "js-page-section-{{index}}"
b. The objective is to get the list of section nodes (above) and then dynamically build out vertical page (nav) navigation based on the n number of nodes found in the query matching selector criteria. Therefore, three sections will result in three page section navigation items. All side navigation start with “js-side-nav-{{index}}>".
c. Once the side navigation is rendered I need to query all the navigation nodes in order to control classes, heights, display, opacity, etc. i.e document.querySelectorAll('*[id^="js-side-nav"]');
EDIT
Based on some research here are the options for my problem. Again my problem being 3 phase DOM state management i.e. STEP 1. Read all nodes equal to x, then STEP 2. Build Side Nav scroll based on n number of nodes in document, and then STEP 3. Read all nav nodes to sync with scroll of document nodes:
Create some sort of event system is $emit() && $on. In my opinion this gets messy very quickly and feels like a poor solution. I found myself quickly jumping to $root
Vuex. but that feels like an overkill
sync. Works but really that is for parent child property state management but that again requires $emit() && $on.
Promise. based service class. This seems like the right solution, but frankly it became a bit of pain managing multiple promises.
I attempted to use Vue $ref but frankly it seems better for managing state rather than multi stage DOM manipulation where a observer event approach is better.
The solution that seems to work is Vues $nextTick(). which seems to be similar to AngularJS $digest. In essence it is a . setTimeout(). type approach just pausing for next digest cycle. That said there is the scenario where the tick doesn’t sync the time requires so I built a throttle method. Below is the code update for what is worth.
The refactored watch with nextTick()
watch: {
'page.sections': {
handler(nodeList, oldNodeList){
if (this.isNodeList(nodeList) && _.size(nodeList) && this.sideNavActive) {
return this.$nextTick(this.sideNavInit);
}
},
deep: true
},
},
The REFACTORED Vue component
<template>
<div v-scroll="handleScroll">
<nav class="nav__wrapper" id="navbar-example">
<ul class="nav">
<li role="presentation"
:id="sideNavPrefix + '-' + (index + 1)"
v-for="(item, key,index) in page.sections">
<a :href="'#' + getAttribute(item,'id')">
<p class="nav__counter" v-text="('0' + (index + 1))"></p>
<h3 class="nav__title" v-text="getAttribute(item,'data-title')"></h3>
<p class="nav__body" v-text="getAttribute(item,'data-body')"></p>
</a>
</li>
</ul>
</nav>
<slot></slot>
</div>
</template>
<script>
import ScrollPageService from '../services/ScrollPageService.js';
const _S = "section", _N = "sidenavs";
export default {
name: "ScrollSection",
props: {
nodeId: {
type: String,
required: true
},
sideNavActive: {
type: Boolean,
default: true,
required: false
},
sideNavPrefix: {
type: String,
default: "js-side-nav",
required: false
},
sideNavClass: {
type: String,
default: "active",
required: false
},
sectionClass: {
type: String,
default: "inview",
required: false
}
},
directives: {
scroll: {
inserted: function (el, binding, vnode) {
let f = function(evt) {
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f);
}
};
window.addEventListener('scroll', f);
}
},
},
data: function () {
return {
scrollService: {},
page: {
sections: {},
sidenavs: {}
}
}
},
methods: {
getAttribute: function(element, key) {
return element.getAttribute(key);
},
updateViewPort: function() {
if (this.scrollService.isInCurrent(window.scrollY)) return;
[this.page.sections, this.page.sidenavs] = this.scrollService.updateNodeList(window.scrollY);
},
handleScroll: function(evt, el) {
if ( !(this.isScrollInstance()) ) {
return this.$nextTick(this.inViewportInit);
}
this.updateViewPort();
},
getNodeList: function(key) {
this.page[key] = this.scrollService.getNodeList(key);
},
isScrollInstance: function() {
return this.scrollService instanceof ScrollPageService;
},
sideNavInit: function() {
if (this.isScrollInstance() && this.scrollService.navInit(this.sideNavPrefix, this.sideNavClass)) this.getNodeList(_N);
},
inViewportInit: function() {
if (!(this.isScrollInstance()) && ((this.scrollService = new ScrollPageService(this.nodeId, this.sectionClass)) instanceof ScrollPageService)) this.getNodeList(_S);
},
isNodeList: function(nodes) {
return NodeList.prototype.isPrototypeOf(nodes);
},
},
watch: {
'page.sections': {
handler(nodeList, oldNodeList){
if (this.isNodeList(nodeList) && _.size(nodeList) && this.sideNavActive) {
return this.$nextTick(this.sideNavInit);
}
},
deep: true
},
},
mounted() {
return this.$nextTick(this.inViewportInit);
},
}
</script>
END EDIT
ORIGINAL POST
Problem & Question:
PROBLEM:
The query of sections and render of navs work fine. However, querying the nav elements fails as the DOM has not completed the render. Therefore, I’m forced to use a setTimeout() function. Even if I use a watch I’m still forced to use timeout.
QUESTION:
Is there a promise or observer in Vue or JS I can use to check to see when the DOM has finished rendering the nav elements so that I can then read them? Example in AngularJS we might use $observe
HTML EXAMPLE
<html>
<head></head>
<body>
<scroll-section>
<div id="js-page-section-1"
data-title="One"
data-body="One Body">
</div>
<div id="js-page-section-2"
data-title="Two"
data-body="Two Body">
</div>
<div id="js-page-section-3"
data-title="Three"
data-body="THree Body">
</div>
</scroll-section>
</body>
</html>
Vue Compenent
<template>
<div v-scroll="handleScroll">
<nav class="nav__wrapper" id="navbar-example">
<ul class="nav">
<li role="presentation"
:id="[idOfSideNav(key)]"
v-for="(item, key,index) in page.sections.items">
<a :href="getId(item)">
<p class="nav__counter">{{key}}</p>
<h3 class="nav__title" v-text="item.getAttribute('data-title')"></h3>
<p class="nav__body" v-text="item.getAttribute('data-body')"></p>
</a>
</li>
</ul>
</nav>
<slot></slot>
</div>
</template>
<script>
export default {
name: "ScrollSection",
directives: {
scroll: {
inserted: function (el, binding, vnode) {
let f = function(evt) {
_.forEach(vnode.context.page.sections.items, function (elem,k) {
if (window.scrollY >= elem.offsetTop && window.scrollY <= (elem.offsetTop + elem.offsetHeight)) {
if (!vnode.context.page.sections.items[k].classList.contains("in-viewport") ) {
vnode.context.page.sections.items[k].classList.add("in-viewport");
}
if (!vnode.context.page.sidenavs.items[k].classList.contains("active") ) {
vnode.context.page.sidenavs.items[k].classList.add("active");
}
} else {
if (elem.classList.contains("in-viewport") ) {
elem.classList.remove("in-viewport");
}
vnode.context.page.sidenavs.items[k].classList.remove("active");
}
});
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f);
}
};
window.addEventListener('scroll', f);
},
},
},
data: function () {
return {
page: {
sections: {},
sidenavs: {}
}
}
},
methods: {
handleScroll: function(evt, el) {
// Remove for brevity
},
idOfSideNav: function(key) {
return "js-side-nav-" + (key+1);
},
classOfSideNav: function(key) {
if (key==="0") {return "active"}
},
elementsOfSideNav:function() {
this.page.sidenavs = document.querySelectorAll('*[id^="js-side-nav"]');
},
elementsOfSections:function() {
this.page.sections = document.querySelectorAll('*[id^="page-section"]');
},
},
watch: {
'page.sections': function (val) {
if (_.has(val,'items') && _.size(val.items)) {
var self = this;
setTimeout(function(){
self.elementsOfSideNavs();
}, 300);
}
}
},
mounted() {
this.elementsOfSections();
},
}
</script>
I hope I can help you with what I'm going to post here. A friend of mine developed a function that we use in several places, and reading your question reminded me of it.
"Is there a promise or observer in Vue or JS I can use to check to see when the DOM has finished rendering the nav elements so that I can then read them?"
I thought about this function (source), here below. It takes a function (observe) and tries to satisfy it a number of times.
I believe you can use it at some point in component creation or page initialization; I admit that I didn't understand your scenario very well. However, some points of your question immediately made me think about this functionality. "...wait for something to happen and then make something else happen."
<> Credits to #Markkop the creator of that snippet/func =)
/**
* Waits for object existence using a function to retrieve its value.
*
* #param { function() : T } getValueFunction
* #param { number } [maxTries=10] - Number of tries before the error catch.
* #param { number } [timeInterval=200] - Time interval between the requests in milis.
* #returns { Promise.<T> } Promise of the checked value.
*/
export function waitForExistence(getValueFunction, maxTries = 10, timeInterval = 200) {
return new Promise((resolve, reject) => {
let tries = 0
const interval = setInterval(() => {
tries += 1
const value = getValueFunction()
if (value) {
clearInterval(interval)
return resolve(value)
}
if (tries >= maxTries) {
clearInterval(interval)
return reject(new Error(`Could not find any value using ${tries} tentatives`))
}
}, timeInterval)
})
}
Example
function getPotatoElement () {
return window.document.querySelector('#potato-scroller')
}
function hasPotatoElement () {
return Boolean(getPotatoElement())
}
// when something load
window.document.addEventListener('load', async () => {
// we try sometimes to check if our element exists
const has = await waitForExistence(hasPotatoElement)
if (has) {
// and if it exists, we do this
doThingThatNeedPotato()
}
// or you could use a promise chain
waitForExistence(hasPotatoElement)
.then(returnFromWaitedFunction => { /* hasPotatoElement */
if (has) {
doThingThatNeedPotato(getPotatoElement())
}
})
})

vuejs - remount after update background url

I have a vue component with the binding style:
<div id="profile-icon" :style="{'background': 'url('+profile.icon+')'}"></div>
<input name="name" v-model="profile.name" type="text" placeholder="Name">
The image will only display if I update the profile.icon under beforeMount function:
props: ['profileprops'],
data: function() {
return {
profile: {
address:'',
name:'Name',
description:'Short description',
address:'address',
user_id:'',
background:'/images/admin/bg.png',
icon:''
},
}
},
beforeMount: function() {
console.log('profileedit mounted.')
var self = this;
if(self.profileprops){
self.profile = self.profileprops;
};
if(!self.profile.icon){
self.profile.icon = '/images/admin/icon-144.png';
},
mounted: function() {
var self = this;
self.$eventHub.$on('ImageSelected', (imagelink) => {///<-- I have another vue component for selecting images to emit event and to catch it here.
self.profile.icon = imagelink;
$('#profilemodal').modal('hide');
});
},
watch: {
'profile': {
handler: function(newVal, oldVal) {
console.log("changed")
},
deep: true
},
}
I did a few tests:
if I select the image, I can see the console.log within the $on has given the correct data from profile.icon. However, the :style did not update the background image with the new profile.icon. And watch.profile did not react at all.
If I start to type on input with v-model bind with profile.name, everything update immediately, including the background image in :style.
I believe I must have miss something to sync the inside and outside of the $on. How can I resolve this?
I found the solution here.
So I just $forceUpdate() inside $on:
self.$eventHub.$on('ImageSelected', (imagelink) => {
self.profile.icon = imagelink;
self.$forceUpdate();//<-- this does the magic.
});
then the data will update and re-render.

React component not re-rendering?

I have a react component that is designed to show a button whenever you are within a certain time limit of when something was created.
var UndoButton = React.createClass({
getDefaultProps: function() {
return ({
timeWindow: 900
})
},
getInitialState: function() {
return ({
commentAge: this.props.timeWindow + 1
})
},
determineDeletable: function() {
this.setState({
commentAge: this.commentAge()
});
},
componentDidMount: function() {
this.determineDeletable()
this.timer = setInterval(this.determineDeletable, 1000);
},
componentWillUnMount: function() {
clearTimer(this.timer);
},
commentAge: function() {
return Math.floor(new Date().getTime() / 1000) - this.props.created_at;
},
inPeriod: function() {
return this.timeRemaining() > 0;
},
timeRemaining: function() {
return this.props.timeWindow - this.state.commentAge;
},
render: function() {
if (!this.inPeriod()) { return false }
return (
<a href='#' className='btn btn-xs btn-default'>Undo Comment ({this.timeRemaining()}s)</a>
)
}
});
Right now, this renders the button within the time window perfectly. However, even though the state is updating every second, the render function does not appear to be running as the time remaining count does not change. Also, when the time window is hit the button doesn't dissapear.
So, what's blocking this React component from rendering the correct information?

Map function doesn't iterate all children

i am building a sidebar for an app, which consists of smaller elements. Right now stuck with an issue where sidebar child element array isn't fully iterated although each child element consists of an unique key. I have a feeling that it might be related to key. :/
Sidebar element component:
var AppSidebar = React.createClass({
getInitialState: function() {
return {
children: []
};
},
getPlaylists: function() {
var that = this;
// returns array of objects
spotify.getMePlaylists(function(err, playlists) {
if(err)
console.error(err);
that.setState({
children: playlists
});
});
},
componentDidMount: function() {
this.getPlaylists();
},
render: function() {
// iterates all children
this.state.children.map(function(playlist) {
console.log(1, playlist.id, playlist.name);
});
var playlists = this.state.children;
return (
<div id="sidebar">
playlists.map(function(playlist) {
// only returns first playlist id and name
console.log(2, playlist.id, playlist.name);
return (<AppSidebarElement key={playlist.id} {...playlist} />);
})}
</div>
);
}
});
Sidebar component:
var AppSidebarElement = React.createClass({
render: function() {
return (
<div className="playlist">
{this.props.name}
</div>
);
}
});
Console output:
1 "75dwLdmL07hDEDWqX17QeE" "The Indie Mix"
1 "2wOXCZ6fJAjpekKlnbg49F" "Interesting artists"
1 "6ULfvJbsdzF7u14dBZo9w1" "chsshhh"
1 "4LJ5hkgqt04IKw454SUJqV" "Motivational Songs"
1 "75if3ukZz2tPS60IVMPhw6" "Best of the Suits Soundtrack"
...
2 "69H6RgTVs1jrv1IuuLe1a5" "Deep Dark Indie"
Issue was caused by code which i cleaned up while posting it to stack-overflow, it was related to calling wrong this within map function context.

Simple Ajax request, that loops over data in React.js

New to react and not 100% on how I should approach this relatively simple problem.
I'm currently looking to gather some images from Reddit, that push those images back to the 'pImage' state.
Then have those said images display within the 'content' div. Usually, I would just go about this with a for loop, but is there a special way I should be processing it with react?
componentDidMount: function() {
var self = this;
$.get(this.props.source, function(result) {
var collection = result.data.children;
if (this.isMounted()) {
this.setState({
//Should I put a for loop in here? Or something else?
pImage: collection.data.thumbnail
});
}
}.bind(this));
}
Fiddle to show my current state: https://jsfiddle.net/69z2wepo/2327/
Here is how you would do it with a map function in the render method:
var ImageCollect = React.createClass({
getInitialState: function() {
return {
pImage: []
};
},
componentDidMount: function() {
var self = this;
$.get(this.props.source, function(result) {
var collection = result.data.children;
if (this.isMounted()) {
this.setState({
pImage: collection
});
}
}.bind(this));
},
render: function() {
images = this.state.pImage || [];
return (
<div>
Images:
{images.map(function(image){
return <img src={image.data.thumbnail}/>
})}
</div>
);
}
});
React.render(
<ImageCollect source="https://www.reddit.com/r/pics/top/.json" />,
document.getElementById('content')
);
Here is working fiddle: http://jsfiddle.net/2ftzw6xd/

Categories

Resources