Why does my program break when I try to refresh the usestate? - javascript

When I try to refresh the usestate my program just breaks. The problematic line is "setMesses(_messages);". I tried to capitalized the usestate but nothing has changed.
import React, {useState} from 'react';
import Message from './Message';
import * as firebase from "firebase";
function MessContainer() {
let counter = 0;
let _messages = [];
const [messes, setMesses] = useState([{this: null}]);
firebase.database().ref().child('counter').on('value', function(snapshot){
counter = snapshot.child("counter").val();
});
function load(_counter){
firebase.database().ref().child('messages/' + _counter).on('value', function(snapshot){
let _chet = {};
let _name = snapshot.child("name").val();
_chet.mess = _name + ": " + snapshot.child("message").val();
if(_name === document.getElementById("name").value){
_chet.status = "right";
} else {
_chet.status = "left";
}
_messages.push(_chet);
});
}
function loadChet(){
_messages = [];
for(let i = 0; i < counter; i++){
load(i);
}
console.log(_messages);
setMesses(_messages);
setTimeout(loadChet, 1000);
}
loadChet();
return (
<div>{messes.map(_mess => (
<Message mess={_mess.mess} status={_mess.status} />
))}
</div>
);
}
export default MessContainer;

The reason why this happens is because you call loadChet and this calls setMesses wich makes the component rerender and call loadChet again, causing a infinity loop.
You shouldn't call loadChet on the function, maybe use useEffect and call it only once will. When do you need to call loadChet ?
Edit:
Try this
function MessContainer() {
let counter = 0;
let _messages = [];
const [messes, setMesses] = useState([{this: null}]);
firebase.database().ref().child('counter').on('value', function(snapshot){
counter = snapshot.child("counter").val();
});
function load(_counter){
firebase.database().ref().child('messages/' + _counter).on('value', function(snapshot){
let _chet = {};
let _name = snapshot.child("name").val();
_chet.mess = _name + ": " + snapshot.child("message").val();
if(_name === document.getElementById("name").value){
_chet.status = "right";
} else {
_chet.status = "left";
}
_messages.push(_chet);
});
}
function loadChet(){
_messages = [];
for(let i = 0; i < counter; i++){
load(i);
}
console.log(_messages);
setMesses(_messages);
setTimeout(loadChet, 1000);
}
useEffect(() => {
loadChet();
}, [])
return (
<div>{messes.map(_mess => (
<Message mess={_mess.mess} status={_mess.status} />
))}
</div>
);
}

Related

Typewriter animation using Vue Js

I'm having an issue and I don't find the answer by myself.
I'm trying to make the following code work. Actually it doesn't work in my Vue project.
const text = document.getElementById("text");
const phrases = [
"I'm John Doe",
"I'm student",
"I'm developer",
];
let currentPhraseIndex = 0;
let currentCharacterIndex = 0;
let currentPhrase = "";
let isDeleting = false;
function loop() {
const currentPhraseText = phrases[currentPhraseIndex];
if (!isDeleting) {
currentPhrase += currentPhraseText[currentCharacterIndex];
currentCharacterIndex++;
} else {
currentPhrase = currentPhrase.slice(0, -1);
currentCharacterIndex--;
}
text.innerHTML = currentPhrase;
if (currentCharacterIndex === currentPhraseText.length) {
isDeleting = true;
}
if (currentCharacterIndex === 0) {
currentPhrase = "";
isDeleting = false;
currentPhraseIndex++;
if (currentPhraseIndex === phrases.length) {
currentPhraseIndex = 0;
}
}
const spedUp = Math.random() * (80 - 50) + 50;
const normalSpeed = Math.random() * (300 - 200) + 200;
const time = isDeleting ? spedUp : normalSpeed;
setTimeout(loop, time);
}
loop();
<h2 id="text"></h2>
As you can see the code is actually working. Checkout the errors I have in my from my Vue Js project.
Do not hesitate, if you have any suggestions to improve my code according to Vue of course.
Try to put variables in data property and function in methods, or i composition api make variables reactive:
const { ref, reactive, onMounted } = Vue
const app = Vue.createApp({
setup() {
const opt = reactive({
currentPhraseIndex: 0,
currentCharacterIndex: 0,
currentPhrase: "",
isDeleting: false
})
const phrases = reactive([
"I'm John Doe",
"I'm student",
"I'm developer"
])
const text = ref('')
const loop = () => {
const currentPhraseText = phrases[opt.currentPhraseIndex];
if (!opt.isDeleting) {
opt.currentPhrase += currentPhraseText[opt.currentCharacterIndex];
opt.currentCharacterIndex++;
} else {
opt.currentPhrase = opt.currentPhrase.slice(0, -1);
opt.currentCharacterIndex--;
}
text.value = opt.currentPhrase;
if (opt.currentCharacterIndex === currentPhraseText.length) {
opt.isDeleting = true;
}
if (opt.currentCharacterIndex === 0) {
opt.currentPhrase = "";
opt.isDeleting = false;
opt.currentPhraseIndex++;
if (opt.currentPhraseIndex === opt.phrases?.length) {
opt.currentPhraseIndex = 0;
}
}
const spedUp = Math.random() * (80 - 50) + 50;
const normalSpeed = Math.random() * (300 - 200) + 200;
const time = opt.isDeleting ? spedUp : normalSpeed;
setTimeout(loop, time);
}
onMounted(() => {
loop()
})
return {
text
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<div id="demo">
<h2>{{ text }}</h2>
</div>
I found the way to make it work.
The following code is updated and works using Vue.js 3.
<script setup>
import { ref } from "vue";
const phrases = [
"I am John Doe.",
"I am student.",
"I am developer.",
];
const currentPhraseIndex = ref(0);
const currentCharacterIndex = ref(0);
const currentPhrase = ref("");
const isDeleting = ref(false);
function loop() {
const currentPhraseText = phrases[currentPhraseIndex.value];
if (!isDeleting.value) {
currentPhrase.value += currentPhraseText[currentCharacterIndex.value];
currentCharacterIndex.value++;
} else {
currentPhrase.value = currentPhrase.value.slice(0, -1);
currentCharacterIndex.value--;
}
if (currentCharacterIndex.value === currentPhraseText.length) {
isDeleting.value = true;
}
if (currentCharacterIndex.value === 0) {
currentPhrase.value = "";
isDeleting.value = false;
currentPhraseIndex.value++;
if (currentPhraseIndex.value === phrases.length) {
currentPhraseIndex.value = 0;
}
}
const spedUp = Math.random() * (80 - 50) + 50;
const normalSpeed = Math.random() * (300 - 200) + 200;
const time = isDeleting.value ? spedUp : normalSpeed;
setTimeout(loop, time);
}
loop();
</script>
<template>
<div>
<h1 id="title">{{ currentPhrase }}</h1>
</div>
</template>
You have to add this line
if (opt.currentCharacterIndex === currentPhraseText.length) {
opt.isDeleting = true;
opt.currentPhraseIndex = 0; // <===== you have to add this line
}

For loop not returning correctly

Why is this for look let returning the correct number of "$" ?
const DollarSignRating = price => {
if (!price || price === 0) {
return "$";
}
let dollarSigns = "";
for (let i = 1; i < price; i++) {
dollarSigns += "$";
}
return dollarSigns;
};
how it's being rendered :
<DollarSignRating price={Math.round(props.restaurant.priceLevels)}/>
You have defined a function and used it as a component!
if you call DollarSignRating(Number) it works correctly. but if you want to use it as a component use this
export defaul DollarSignRating = ({price}) => {
if (!price || price === 0) {
return <h1>"$"</h1>;
}
let dollarSigns = "";
for (let i = 1; i < price; i++) {
dollarSigns += "$";
}
return <h1>{dollarSigns}</h1>;
};
in each component, you should return an html code like h1.
now you can use it as follows:
<DollarSignRating price={your number} />

How to make regular javascript work in a react app

Hi I was trying to implement this text scrable
https://codepen.io/soulwire/pen/mErPAK/?editors=1010
in my react app, but I'm receiving an error TypeError: Cannot read property 'innerText' of null.
9 | this.update = this.update.bind(this)
10 | }
11 | setText(newText) {
> 12 | const oldText = this.el.innerText
13 | const length = Math.max(oldText.length, newText.length)
14 | const promise = new Promise(resolve => (this.resolve = resolve))
15 | this.queue = []
so far this is what I did
https://codesandbox.io/s/oxm38v7x9y
Created new component scrable.js
Moved the code from codepen
Imported to index.js
you don't need to fix the codesandbox, just a little clue is enough :)
import React, { Component } from "react"
export default class Scrable extends Component {
render() {
const phrases = [
"Neo,",
"sooner or later",
"you're going to realize",
"just as I did",
"that there's a difference",
"between knowing the path",
"and walking the path",
]
const el = document.querySelector(".text")
const fx = new TextScramble(el)
console.log(el)
let counter = 0
const next = () => {
fx.setText(phrases[counter]).then(() => {
setTimeout(next, 800)
})
counter = (counter + 1) % phrases.length
}
next()
return (
<TextScramble>
<div className="text" />
</TextScramble>
)
}
}
export class TextScramble extends Component {
constructor(el) {
super()
this.el = el
this.chars = "!<>-_\\/[]{}—=+*^?#________"
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise(resolve => (this.resolve = resolve))
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ""
const to = newText[i] || ""
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({ from, to, start, end })
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ""
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
} else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
render() {
return <div />
}
}
Hi all thank you for the comments,
I was able to make it work. here's my code below. any suggestions is welcome
I'm not entirely sure it's the right way but it works
import React, { Component } from 'react'
export default class Scrable extends Component {
constructor(el) {
super(el)
this.el = el
this.chars = "!<>-_\\/[]{}—=+*^?#________"
// this.update = this.update.bind(this)
}
componentDidMount(){
const phrases = [
'Neo,',
'sooner or later',
'you\'re going to realize',
'just as I did',
'that there\'s a difference',
'between knowing the path',
'and walking the path'
]
const el = document.querySelector('.text')
const fx = new TextScramble(el)
let counter = 0
const next = () => {
fx.setText(phrases[counter]).then(() => {
setTimeout(next, 800)
})
counter = (counter + 1) % phrases.length
}
next()
console.log(el)
}
render() {
const phrases = [
"Neo,",
"sooner or later",
"you're going to realize",
"just as I did",
"that there's a difference",
"between knowing the path",
"and walking the path",
]
return (
<div>
<div className="text">text</div>
</div>
)
}
}
class TextScramble {
constructor(el) {
this.el = el
this.chars = '!<>-_\\/[]{}—=+*^?#________'
this.update = this.update.bind(this)
console.log(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({ from, to, start, end })
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
} else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}

JavaScript - Uncaught ReferenceError: checkAnswer is not defined, function not in the scope?

class Pairs extends Screen {
constructor() {
super();
var pair1 = null;
var nPair1;
var solution;
var rightCounter = 0;
var licao, nS;
}
pairScreen(screen, lesson, nScreen) {
var body = document.body
var nodes = xmlDoc.getElementsByTagName("PAIRS");
this.licao = lesson;
this.nS = nScreen;
this.solution = screen.getElementsByTagName("SOLUTION")[0].textContent.split(" ");
body.innerHTML = '';
Startup.h1(body, "Babel (" + languageName + ")");
Startup.hr(body);
var d = DynamicHTML.div(body, "border:3px solid black; display:table; padding:20px; margin-left:40px");
Startup.h1(d, "Match the pairs");
var p1 = Startup.p(d, "padding-left:40px; word-spacing:50px;");
Startup.text(p1, 16, " ");
Startup.text(p1, 32, " ");
var p2 = Startup.p(d, "padding-left:20px;");
var button;
var i;
var f = function(i) {
Startup.eventHandler2()
}
var original = screen.getElementsByTagName("ORIGINAL")[0].textContent;
var buttons = original.split(" ");
for (i = 0; i < buttons.length; i++) {
button = DynamicHTML.inpuButton(p1, i, buttons[i], "orangered");
Startup.eventHandler2(document.getElementById(i), "onclick", function() {
checkAnswer(buttons[i], i)
});
}
Startup.hr(body);
}
checkAnswer(pair, nPair) {
var index;
if (pair1 = null) {
pair1 = pair;
nPair1 = nPair;
} else {
for (index = 0; index < solution.length; index++) {
if (pair1 == solution[index]) {
if (index % 2 == 0 && solution[index - 1] == pair) {
DynamicHTML.play("general/right_answer.mp3");
rightCounter = rightCounter + 2;
document.getElementById(nPair).disabled = true;
document.getElementById(nPair1).disabled = true;
pair1 = null;
nPair1 = null;
} else if (solution[index + 1] == pair) {
DynamicHTML.play("general/right_answer.mp3");
rightCounter = rightCounter + 2;
document.getElementById(nPair).disabled = true;
document.getElementById(nPair1).disabled = true;
pair1 = null;
nPair1 = null;
} else {
DynamicHTML.play("general/wrong_answer.mp3");
pair1 = null;
nPair1 = null;
}
}
}
}
if (rightCounter == solution.length) {
if (xmlDoc.getElementsByTagName("LESSON")[licao].childNodes[nS + 2] != null) {
var fs = new Screen();
fs.functionScreen(licao, nS + 2);
} else fs.initialScreen();
}
}
}
Wrote this for a JavaScript project I'm working on but when I run it It says Uncaught ReferenceError: checkAnswer is not defined, I'd really appreciate if anyone knew the problem. Thank you!
P.S. Don't know if the checkAnswer function has bugs or note becausa I couldn't test it out, I will when I can run it :)
First you need to bind this at the end of this function:
Startup.eventHandler2(document.getElementById(i), "onclick", function() {
this.checkAnswer(buttons[i], i)
}.bind(this));
Basically this tells the anonymous function "hey I want this to refer to this outer class, not the function itself".
(edited)
You need to either bind checkAnswer in the constructor like-so:
class Pairs extends Screen {
constructor() {
super();
var pair1 = null;
var nPair1;
var solution;
var rightCounter = 0;
var licao, nS;
this.checkAnswer = this.checkAnswer.bind(this);
}
Or use and arrow function which gives you the exact reference to the this checkAnswer like-so:
checkAnswer = (pair, nPair) => {
//your code goes here ...
}
This way you will be able to call this.checkAnswer inside the scope of your pairScreen function or wherever you want to call the function like #Davelunny point out

Redux doesn't behave correctly

I just learned a little of react-redux and stuck at such problems I cannot understand and fix at least 4 days long.
First of the problem stands and can be seen at inspectors console (I use Chrome).
I have event handler at <div> inside react component. It have to be called at onClick event but it triggers at each load or reload of site.
Second, stands somewhere near reducer's function. It says me in console (dev tools) that reducers received action 'TOGGLE_TILE' and returned undefined instead of object. Should notice that reducer successfully receives state, action properties and makes some operations inside but as result nothing normal returnes.
The code of my reducer, actions, main, container, presentation components and functions provide. Please answer expanded as you can, i want to understand whats wrong and not make this mistake inside code twice.
ALSO! I using redux-thunk middleware (to functional callbacks inside actions, you know).
Inside i have:
index.js - main component
const store = createStore(reducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<AppContainer />
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
actions.js
export function toggle(id){
return{
type: 'TOGGLE_TILE',
id
};
}
export function toggleTile(id){
return dispatch => {
console.log('toggling');
dispatch(toggle(id));
};
}
tiles.js - Reducer
var i = 0;
function tiles(state = tilesContainer, action){
var openedTiles = [];
switch (action.type) {
case 'TOGGLE_TILE':
if(i < 2){
console.log('i: '+i);
state.map((value) => {
var newOpen;
if(!value.opened && action.id === value.id){
newOpen = Object.assign({}, value, {
opened: !value.opened
});
openedTiles.push(newOpen);
i++;
console.log(i, value.opened, newOpen, openedTiles);
}
return newOpen, i;
});
}else if(i === 2){
var curr, prev;
openedTiles.map((value) => {
if(!prev){
prev = value;
}else{
curr = value;
console.log("Prev and curr: "+prev, curr);
if(curr.name === prev.name){
var currRes = Object.assign({}, curr, {
disappeared: !curr.disappeared
});
var prevRes = Object.assign({}, prev, {
disappeared: !prev.disappeared
});
return {currRes, prevRes};
} else {
let currRes = Object.assign({}, curr, {
opened: !curr.opened
});
let prevRes = Object.assign({}, prev, {
opened: !prev.opened
})
return currRes, prevRes;
}
}
});
}else{
return state;
}
default:
return state;
}
console.log("tiles: "+state.forEach(value => console.log(value)));
}
const reducers = combineReducers({
tiles
});
export default reducers;
AppContainer.jsx
const mapStateToProps = (state) => {
return {
tiles: state.tiles
};
};
const mapDispatchToProps = (dispatch) => {
return {
toggle: id => {
// console.log(id);
dispatch(toggleTile(id));
}
};
};
class AppContainer extends Component {
constructor(props){
super(props);
}
componentDidMount(){
}
render() {
var prop = this.props;
console.log(prop);
return (
<div>
<AppView prop={prop} />
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
AppView.js
class AppView extends React.Component {
constructor(props){
super(props);
this.state = {
tiles: this.props.prop.tiles,
};
this.showTiles = this.showTiles.bind(this);
this.defineRatio = this.defineRatio.bind(this);
this.toggleTile = this.toggleTile.bind(this);
}
componentDidMount(){
this.defineRatio();
}
componentWillMount(){
}
defineRatio(){
var imgClass;
let tile = document.querySelectorAll('img');
tile.forEach((value) => {
var imgSrc, imgW, imgH;
function defineImage(imgSrc){
var img = new Image();
img.src = imgSrc;
img.onload = function() {
return {
src:imgSrc,
width:this.width,
height:this.height};
};
return img;
}
var x = defineImage(value.src);
x.addEventListener('load',function(){
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
// console.log(value.src, imgW, imgH);
var imgClass = (imgW / imgH > 1) ? 'wide' : 'tall';
value.classList += imgClass;
});
});
}
toggleTile(id){
this.props.prop.toggle(id);
}
showTiles(){
const boxElems = this.state.tiles.map((value, index) => {
var styles = {background: 'black'};
var tileState = value.opened ? '' : styles;
var imgState = value.opened ? 'opened ' : 'closed ';
var elem = <img key={value.id} src={value.src} alt="" className={imgState} />;
var boxElem = <div style={tileState} className="tile-box " onClick={this.toggleTile(value.id)} key={index}>{elem}</div>;
return boxElem;
});
return boxElems;
}
render(){
var tiles = this.showTiles();
return (
<div className="tiles-box">
<div className="tiles">
{tiles}
</div>
</div>
);
}
}
export default AppView;
First problem can be solved by replacing
onClick={this.toggleTile(value.id)}
with onClick={(e) => this.toggleTile(value.id)} First statement is just invoking this.toggleTile(value.id) immediately and setting the return value to OnClick event.
Regarding second you are not returning any thing from your reducer , hence state is undefined.
if(i < 2){
console.log('i: '+i);
state.map((value) => {
var newOpen;
if(!value.opened && action.id === value.id){
newOpen = Object.assign({}, value, {
opened: !value.opened
});
openedTiles.push(newOpen);
i++;
console.log(i, value.opened, newOpen, openedTiles);
}
return newOpen, i;
});
}
What is this return newOpen, i it should be return newOpen, also as this return is in a map function you have to return the mapped array as well
so use return state.map((value) => {
the problem that you have is that you are actually calling the function inside your div, thus it will get triggered each time you enter the view, so replace the following code on your showTiles()
var boxElem = <div style={tileState} className="tile-box " onClick={this.toggleTile(value.id)} key={index}>{elem}</div>;
to this:
var boxElem = <div style={tileState} className="tile-box " onClick={e => this.toggleTile(value.id)} key={index}>{elem}</div>;
and actually this should fix the error for the point 2.

Categories