React, trying to return props from json

I am just trying to experiment with an app, and in my html I am trying to return the props of userData which in my console logs things such as lineStatus etc, however I seem to be returning nothing.

my code is as follows:

import React, { useState, useEffect } from 'react'
import axios from "axios";

const tflData = "https://api.tfl.gov.uk/line/mode/tube/status";

axios.request(tflData).then(function (response) {
    console.log(response.data);
}).catch(function (error) {
    console.error(error);
});

function Lines() {
    
    const [userData, setUserData] = useState({});
    const tflUserWithFetch = async () => {
        const response = await fetch(tflData);
        const jsonData = await response.json();
        setUserData(jsonData);
      };

  useEffect(() => {
    tflUserWithFetch();
  }, []);
  
  return (
    <div className="App">
      <header className="App-header">
        <h2>Line Data</h2>
      </header>
      <div className="user-container">
        <h5 className="info-item">Tube station: {userData.name}</h5>
        <h5 className="info-item">Status: {userData.lineStatuses}</h5>
     
      </div>
    </div>
  );
}

export default Lines

Basically I am trying to return the values or content values but I am missing something.

How do I check whether an element is already bound to an event?

Goal

Avoid unnecessary event bindings.

Sample code

Comment box with a reply button for each individual comment

const btns = document.getElementsByClassName('reply-btn');

for (let i = 0; i < btns.length; i++) {    
  btns[i].addEventListener('click', showCommentContentAsPreview);
}


function showCommentContentAsPreview(e) {
  console.log('showCommentContentAsPreview()');
  
  // CHECK IF THIS BUTTON ALREADY BINDED !!!
  const previewDiv = document.getElementById('preview');
  const commentId = e.target.getAttribute('data-comment-id')
  const commentDiv = document.getElementById('comment-' + commentId);
  const commentText = commentDiv.querySelector('p').innerText
  const closeReplyBtn = previewDiv.querySelector('button');
  const previewContent  = previewDiv.querySelector('.preview-content');
  
  // set to preview
  previewContent.innerText = commentText;
  
  // show reply close button  
  closeReplyBtn.classList.remove('hidden');
  
  // bind EventListener to "reply close button"
  closeReplyBtn.addEventListener('click', closeReply)
  
  function closeReply() {
    console.log('bind to btn');
    previewContent.innerText = '';
    this.removeEventListener('click', closeReply);
    closeReplyBtn.classList.add('hidden');
  }
}
.hidden {
  display: none;
}

.comment {
  border-bottom: 1px solid #000;
  padding: 5px;
}


.preview {
  background-color: #ccc;
  padding: 20px;
  margin-top: 20px;
}
<div>
  <!-- comment list -->
  <div id="comment-1" class="comment">
    <p>Comment Content 1</p>
    <button class="reply-btn" data-comment-id="1">reply</button>
  </div>
  
  <div id="comment-2"  class="comment">
    <p>Comment Content 2</p>
    <button  class="reply-btn" data-comment-id="2">reply</button>
  </div>  
</div>

<!-- output -->
<div>
  <div id="preview" class="preview">
    <div class="preview-content"></div>
    <button class="hidden">Close Preview</button>
  </div>
</div>

Simulate problem

When you try the example, the following two scenarios occur:

  1. Click reply once and then click “close preview”

  2. Click on reply several times and then on “close preview”.

Question

How can I avoid multiple bindings to the same button? I am already thinking about singleton.

Problem with updating object property in array of objects in React

I’m making an ecommrece project, in search bar I’m displaying checkboxes with categories from the API, all of those have value active == true by default. This is how I’m mapping them:

{categories.map((category) => {
       return (
              <>
             <input type="checkbox" onClick={() => handleCheckbox(category)} 
             defaultChecked={category.active} key={category.name} />
             <label style={{marginLeft:"5px"}} htmlFor={category.name}>{category.name}</label><br/>
             </> 
)
})}

Then I run this function to change category.active property from true to false, when the exact checkbox is clicked, then I want to update this object using useState

const handleCheckbox = (category) => {
    let tempCategory = category
    if (tempCategory.active == true) {
        tempCategory.active = false;
    } else {
        tempCategory.active = true;
    }
    setCategories({...categories, [tempCategory.id]: tempCategory})
    console.log(category.active)
}

Unfortunetly when I click on the checkbox I’m getting an error from React:

TypeError: categories.map is not a function

And it points to categories.map, I have no idea how to fix it. All I want is to update specific object in the categories array.

unable to connect to nodejs server from react client with SocketIO

I’m learning socketIO and I set up and running a basic nodejs server . My problem is that when I try to connect to the server with my nextJS app nothing happens. No errors occur and the messages I want to be printed on connection do not appear .

My code :

server.js in backend folder

const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidV4 } = require('uuid');
const cors = require('cors');

const io = require('socket.io')(server, {
  cors: true,
  origins:["http://localhost:3000"]
});



app.use(cors());
app.options('*', cors());



io.on('connection', socket => {
  socket.on('test',()=>{
   console.log(' i am a test') //does not appear 
  })
  
})





   //I ALSO TRIED 
   //io.on('test',()=>{
       //console.log('I am a test');
     //})


server.listen(5000);

Then in my nextJS app in my frontend folder in index.js

import {useEffect} from 'react';
import io from 'socket.io-client';

const ENDPOINT = "http://localhost:5000";
const socket = io.connect(ENDPOINT);

  export default function Home() {

    useEffect(()=>{

     socket.emit('test');
    },[]);
    
   ...rest of code 
   
 }

So in my frontend app I emit the ‘test’ event to the server and the server did not console.log the response on connection

I would appreciate your help as I am new to socketIO

javascript numbers to multiply

Hey guys I’m trying to multiply 2 numbers that are smaller than 1000 and bigger than 0 and i want alert messages to pop up if the numbers are bigger than a thousand or not a number. The problem is that the alert message shows up every time I click the button.. any tips?

function buttonAction5() {

  var z = document.getElementById("number1").value;
  var y = document.getElementById("number2").value;
  
  if (z< 1000 || y < 1000 && z > 0|| y > 0); {
    document.getElementById("result5").innerHTML = y * z;
    
  }
  if  (isNaN(y || z)){
    alert("Please write a number between 1-1000"); 
  }
  
  else (z || y > 1000 && z || y < 0);{
    alert("Please write a number between 1-1000");
   
  }

  } 

response data is undefined for a moment

I’m trying to retrieve data from an Api.
When I log the response data, everything looks fine. When i load my component I get ‘undefined’ on each place where I should have data from the Api. When I press on my sidebar, every ‘undefined’ turns into the right data. I think that I encounter some problem with the asynchronous behaviour of my calls but I don’t realy know how to solve this problem.

For information : I’m using ReactJs

function Dashboard() {
  const [isLoading, setIsLoading] = useState(true);
  const [loadedDataFromApi, setLoadedDataFromApi] = useState([]);

  //some other vars
 
  useEffect(() => {
    setIsLoading(true);
    fetch(`https://soccer.sportmonks.com/api/v2.0/fixtures/between/${todayString}/${inTenDaysString}?api_token=oAF3XOevLeC24Zjuzvu56vfOfvyrmHSd11eHr4Ij6ifeJq563NzHeKFrLaJy`
    )
      .then((response => {
        return response.json();
      }))
      .then((response => {

        //FOREACH to loop over every {} in the []
        response.data.forEach((data) => {

          var localTeam = data.localteam_id;
          var visitorTeam = data.visitorteam_id;

          var docRef1 = db.collection("Teams").doc(`${localTeam}`)
          var docRef2 = db.collection("Teams").doc(`${visitorTeam}`)

          docRef1.get().then((doc) => {
            if (doc.exists) {
              data.localTeam = doc.data().name;
              data.logoLocalTeam = doc.data().logo;
            } else {
              // doc.data() will be undefined in this case
              console.log("No such Team found!");
            }
          }).catch((error) => {
            console.log("Error getting document:", error);
          });

          docRef2.get().then((doc) => {
            if (doc.exists) {
              data.visitorTeam = doc.data().name;
              data.logoVisitorTeam = doc.data().logo;
            } else {
              // doc.data() will be undefined in this case
              console.log("No such Team found!");
            }
          }).catch((error) => {
            console.log("Error getting document:", error);
          });
        })

        setLoadedDataFromApi(response.data);
        setIsLoading(false);

      }))

  }, [todayString, inTenDaysString])

  // if we are loading the data return loading .. 
  if (isLoading) {
    return (
      <section>
        <p>Loading ...</p>
      </section>)
  }

  return (
  // some code ) 

Vuejs – Is it possible to convert an living instance back to template?

Is it possible to convert an living component instance back to template?

Currently I am working on a form-making website with element-ui and VueJS. I have finish the <preview /> component. It will present the editing result to the user, and now I need to export the whole result form as VueJS template.

Since the result form is simply made up of a whole bunch of element-ui‘s form input components, like <el-input>, <el-button>. it might be possible to convert them back to template. But soonly I realized it is not as simple as I throught. I tried doing this by treversing the virtual dom tree, but ended up discorvering that Vue.js doesn’t offer public vnode treversing API. there is an instance attribute named $vnode, but it is the the placeholder node for the component in parent’s render tree, according to the source code comment. Besides, it’s children property is undefined. that means I cannot access the children vnodes, thus become impossible to treverse the virtual DOM tree. Another way is use the private property _vnode, it is feasible way though, but the property is private and I’d rather not touch it, unless I have no other ways.

Another problem I realized later, is that the vdom tree doesn’t keep the informations about v-if. One the current true branch will remains in the virtual DOM tree, and I cannot withdraw other false/invisible tags from the vdom tree.

So it looks treversing the DOM tree cannot convert an instance back to template (or maybe I am wrong). Is it some other ways that can accomplish my goal?

what’s the meaning of “ERR_ACCESS_DENIED” in chrome?

I have some issue about “ERR_ACCESS_DENIED”, I deploy a website server, and there is a upload file function,but recently it doesn’t work, I checked the chrome console, in Network tab, it shows “(failed)net::ERR_ACCESS_DENIED”, I don’t known why because I do not change my code recently, and the request didn’t arrive my background program which is a java web process(debug breakpoint), even the nginx, so what’s ths meaning of “ERR_ACCESS_DENIED”, Does this have anything to do with the chrome version? please give me some help

How to write functions when type of values are different?

I have a problem with making my function smarter. I achieve good results, but I think about the other solution.

I can take boolean or object as parameter. When the parameter is the object I’d like to keep it as now. When the parameter is a boolean value, I’d like to create an object, where keys are taken from another variable (less important) and values are this boolean.

My solution assumes

  • adding an empty items object at the beginning
  • reading what is a value type and setting items according to the conditions
  • taking items and converting to an array
  • saving the array in state

Is that OK?

Check my code

const onAddAll = value => {
        let items = {}

        if (typeof value === 'boolean') {
            terms.forEach(term => items[ term ] = value)
        }

        if (typeof value === 'object') {
            items = value
        }

        const checked = Object.keys(items).filter(k => items[ k ])
        setChecked(checked)
    }

Imo, I wouldn’t need the second condition and make it smarter, bot no idea how. Please help!

MUI textfield loses focus when selected

At one stage this textfield was working fine but now every time it is selected it just loses focus immediately, so I am unable to input any text.

      <InputField
        fullWidth
        placeholder="enter text"
        value={text}
        onChange={(e) => setText(e.value)}
        onFocus={undefined}
      />

This causes loss of focus:

const InputField = ({ onChange, onFocus, ...textFieldProps }) => {
  if (onFocus) {
    return (
      <TextField
        onChange={(event) => onChange(event.target.value)}
        onFocus={(event) => onFocus(event.currentTarget)}
        {...textFieldProps}
      />
    );
  } else {
    return (
      <TextField
        onChange={(event) => onChange(event.target.value)}
        {...textFieldProps}
      />
    );
  }
};

Without the conditional it works fine:

const InputField = ({ onChange, onFocus, ...textFieldProps }) => {
    return (
      <TextField
        onChange={(event) => onChange(event.target.value)}
        {...textFieldProps}
      />
    );
};

I want to make a toggle button in a check box somewhere else

I’d like to inquire.
I created a page with a product list.
If you press the “Inquiry” button at the top, the inquiry form comes down, and there is a product list check box in it.

In the list of products outside, click the “Add to Inquiry” button in the list to check the check box of the inquiry form.
At this time, I want to release the checkbox check by pressing the “Add to Inquiry” button again. It functions like “Toggle”.

https://thepagegallery49.cafe24.com/wp/publication/

The code I used is as follows.

List ‘Inquire Button’

                <div class="news-text-box">
                <span class="addbtn" id="<?php the_sub_field('pbtag'); ?>"><span class="addon active">Add in Inquire</span><span class="addoff">Added</span></span>             </div>

Javascript

    document.getElementById("<?php the_sub_field('pbtag'); ?>").addEventListener("click", () => {
    document.querySelector('input[value="<?php the_sub_field('pbtitle'); ?>"]').checked = true;
    document.querySelector('input[value="<?php the_sub_field('pbtitle'); ?>"]').parentElement.classList.toggle('active');
})

Checkbox

<ul id="wpforms-187-field_28">
<li class="choice-1 depth-1"><input type="checkbox" id="wpforms-187-field_28_1" name="wpforms[fields][28][]" value="Matters of Life and Death"><label class="wpforms-field-label-inline" for="wpforms-187-field_28_1">Matters of Life and Death</label></li>
<li class="choice-2 depth-1 active"><input type="checkbox" id="wpforms-187-field_28_2" name="wpforms[fields][28][]" value="Displacements"><label class="wpforms-field-label-inline" for="wpforms-187-field_28_2">Displacements</label></li>
...
</ul>

Video does not stop playing when clicking out the popped up box in JWPlayer

I’m using jwplayer and I have coded this at the end of body:

<script src="{{asset('js/jwplayer/jwplayer.js')}}"></script>
<script type="text/JavaScript">
        jwplayer("video1").setup({
            sources: [{
                file: "http://video.sitename.com/filename.mp4",
                label: "360",
                "default": "true"
            }],
        });
</script>

And this is the html part:

<!-- Modal body 1 -->
<div class="modal-body">
   <div id="video1"></div>
</div>

So it loads the video perfectly but when the user clicks outside the box or clicks the close link (x), the video sound can be still heard!

However, the video is closed.

So how can I properly fix this so that if the user clicks anywhere outside of the Modal box or if he clicks on x, the video will be closed COMPLETEY?

Are there javascript commands to determine the first and last fully visible line in an html-textarea?

A part of a very large file is loaded and shown in an textarea. When the user hits the page up or down button, the javascript should determine the last fully shown line with a line break visible in the textare, respectivly the first fully shown line visible, and which cursor position that last line break or first shown character is of the textareas text. Then I could determine what to do next (only scroll the textarea or load a new part of the very large file).

Vue Prevent form submit when pressing enter inside form

I have a webapp with multiple forms and inside these forms multiple custom made components: input, textarea, selectbox, datepicker, radiobutton, checkbox, … .

I found out that the submit function is fired when pressing the enter key inside a child component of a form tag. Something I don’t want. I want to be able to use the enter key for other things like conforming a selection in a dropdown.

Form example

<template>
    <form @submit.prevent="handleLogin">
        <fieldset :disabled="isSubmitting" class="space-y-6">
            <Input :label="$tc('email', 1)" type="email" id="email" v-model="user.email" :error="errors.email" />
            <Input :label="$tc('password', 1)" type="password" id="password" v-model="user.password" :error="errors.password" />
            <Select :label="$tc('role', 1)" id="role" :options="roles" displayProperty="display_name" valueProperty="id" v-model="user.role" :error="errors.role" />
            <SubmitButton :label="$tc('register', 1)" :submittingLabel="$tc('register_loader', 1)" :isSubmitting="isSubmitting" />
        </fieldset>
    </form>
</template>

SubmitButton.vue

<button type="submit">{{ isSubmitting ? submittingLabel : label }}</button>

Therefore I’m looking for a way to prevent the default behaviour. Adding a keydown function and checking if the enter key is being pressed inside all the custom components followed by an event.preventDefault() didn’t do the trick.

A working solution should be to change the type of the button from ‘submit’ to ‘button’ and use an @click but that doesn’t sound like semantic html.

Any other suggestions?