setState updates state and triggers render but Is till don’t see it in view

I have a simple word/definition app in React. There is an edit box that pops up to change definition when a user clicks on “edit”. The new definition provided is updated in the state when I call getGlossary(), I see the new definition in inspector and a console.log statement in my App render() function triggers too. Unfortunately, I still have to refresh the page in order for the new definition to be seen on screen. I would think that calling set state for this.state.glossary in the App would trigger a re-render down to GlossaryList and then to GlossaryItem to update it’s definition but I’m not seeing it :(.

App.js

import React from "react";
import GlossaryList from './GlossaryList.jsx';
import SearchBox from './SearchBox.jsx';
import AddWord from './AddWord.jsx';
const axios = require('axios');


class App extends React.Component {
  constructor() {
    super();
    this.state = {
      glossary: [],
      searchTerm: '',
    }

    this.getGlossary = this.getGlossary.bind(this); //not really necessary?
    this.handleSearchChange = this.handleSearchChange.bind(this);
    this.handleAddGlossaryItem = this.handleAddGlossaryItem.bind(this);
    this.handleDeleteGlossaryItem = this.handleDeleteGlossaryItem.bind(this);
    //this.handleUpdateGlossaryDefinition = this.handleUpdateGlossaryDefinition.bind(this);
  }

  getGlossary = () => {
    console.log('getGlossary fired');
    axios.get('/words').then((response) => {
      const glossary = response.data;
      console.log('1: ' + JSON.stringify(this.state.glossary));
      this.setState({ glossary }, () => {
        console.log('2: ' + JSON.stringify(this.state.glossary));
      });

    })
  }

  componentDidMount = () => {
    //console.log('mounted')
    this.getGlossary();
  }

  handleSearchChange = (searchTerm) => {
    this.setState({ searchTerm });
  }

  handleAddGlossaryItem = (glossaryItemToAdd) => {
    //console.log(glossaryItemToAdd);
    axios.post('/words', glossaryItemToAdd).then(() => {
      this.getGlossary();
    });
  }

  handleDeleteGlossaryItem = (glossaryItemId) => {
    console.log('id to delete: ' + glossaryItemId);
    axios.delete('/words', {
      data: { glossaryItemId },
    }).then(() => {
      this.getGlossary();
    });
  }

  render() {
    console.log('render app fired');
    const filteredGlossary = this.state.glossary.filter((glossaryItem) => {
      return glossaryItem.word.toLowerCase().includes(this.state.searchTerm.toLowerCase());
    });

    return (
      <div>
        <div className="main-grid-layout">
          <div className="form-left">
            <SearchBox handleSearchChange={this.handleSearchChange} />
            <AddWord handleAddGlossaryItem={this.handleAddGlossaryItem} />
          </div>
          <GlossaryList
            glossary={filteredGlossary}
            handleDeleteGlossaryItem={this.handleDeleteGlossaryItem}
            getGlossary={this.getGlossary}
          //handleUpdateGlossaryDefinition={this.handleUpdateGlossaryDefinition}
          />
        </div>
      </div>
    );
  }
}

export default App;

GlossaryItem.jsx

import React from 'react';
import EditWord from './EditWord.jsx';
const axios = require('axios');

class GlossaryItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isInEditMode: false,
    }
    this.glossaryItem = this.props.glossaryItem;
    this.handleDeleteGlossaryItem = this.props.handleDeleteGlossaryItem;
    this.handleUpdateGlossaryDefinition = this.handleUpdateGlossaryDefinition.bind(this);
    this.handleEditClick = this.handleEditClick.bind(this);
  }

  handleUpdateGlossaryDefinition = (updateObj) => {
    console.log('update object: ' + JSON.stringify(updateObj));
    axios.put('/words', {
      data: updateObj,
    }).then(() => {
      this.props.getGlossary();
    }).then(() => {
      this.setState({ isInEditMode: !this.state.isInEditMode });
      //window.location.reload();
    });
  }

  handleEditClick = () => {
    // display edit fields
    this.setState({ isInEditMode: !this.state.isInEditMode });
    // pass const name = new type(arguments); data up to App to handle with db
  }

  render() {
    return (
      <div className="glossary-wrapper">
        <div className="glossary-item">
          <p>{this.glossaryItem.word}</p>
          <p>{this.glossaryItem.definition}</p>
          <a onClick={this.handleEditClick}>{!this.state.isInEditMode ? 'edit' : 'cancel'}</a>
          <a onClick={() => this.handleDeleteGlossaryItem(this.glossaryItem._id)}>delete</a>
        </div>
        {this.state.isInEditMode ?
          <EditWord
            id={this.glossaryItem._id}
            handleUpdateGlossaryDefinition={this.handleUpdateGlossaryDefinition}
          /> : null}
      </div>
    );
  }
}

EditWord

import React from 'react';

class EditWord extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      definition: ''
    };

    this.handleUpdateGlossaryDefinition = this.props.handleUpdateGlossaryDefinition;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    let definition = event.target.value;
    this.setState({ definition });
  }

  handleSubmit(event) {

    //console.log(event.target[0].value);
    let definition = event.target[0].value;
    let update = {
      'id': this.props.id,
      'definition': definition,
    }
    //console.log(update);
    this.handleUpdateGlossaryDefinition(update);
    event.preventDefault();

  }

  render() {
    return (
      <form onSubmit={this.handleSubmit} className="glossary-item">
        <div></div>
        <input type="text" name="definition" placeholder='New definition' value={this.state.definition} onChange={this.handleChange} />
        <input type="submit" name="update" value="Update" />
      </form>
    );
  }
}
export default EditWord;

Thank youenter image description here

Keep Google OAuth User Logged-in on Refresh

I’m using the Google Calendar API and can’t figure out how to keep the user logged in when they refresh the page. I can’t find anything online about this. If anyone could help, it’d be greatly appreciated! This is my current code to login the user:

function handleAuthClick() {
    tokenClient.callback = async (resp) => {
        if (resp.error !== undefined) {
            throw (resp);
        }
        await listUpcomingEvents();
    };

    if (gapi.client.getToken() === null) {
        tokenClient.requestAccessToken({prompt: 'consent'});
    } else {
        tokenClient.requestAccessToken({prompt: ''});
    }
}

My body element automatically runs this on load. I’m using this guide: https://developers.google.com/calendar/api/quickstart/js.

How to implement a function that matches a specific paragraph in JavaScript?

full url : abc.com/product/123

find url : abc.com/product

I want to return true if the full url contains find url

The condition must match the sentences of find url and the words in the full url perfectly.

fullurl.indexOf('abc') // this find true It is a condition that only certain words should not be split.

I want the result value

fullurl = 'abc.com/product/123'; 
findurl = 'abc.com/product';

fullurl.indexOf('abc'); // this find false 
fullurl.indexOf('pro'); // this find false 
fullurl.indexOf('abc.com'); // this find false 
fullurl.indexOf('abc.com/product'); // this true This result is the return value I want

I can’t get the result I want with the indexOf function alone. What should I do?

Google Sheets – Find last column with data in array

I’m trying to find the last column in a range, but the problem is I can’t specify the script to only check within an array instead of the entire sheet. I was able to use this bit of code to find the last row but I’m having trouble understanding how this can be changed to find the column instead of row.

function findLastRow() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const data = sh.getRange("A:K").getValues();
  const mR = sh.getMaxRows();
  const indexes = [];
  data[0].forEach((_,ci)=>{
   let col = data.map(d => d[ci]);
   let first_index = col.reverse().findIndex(r=>r!='');
   if(first_index!=-1){
      let max_row = mR - first_index;
      indexes.push(max_row);
   }
  });
  last_row = indexes.length > 0 ? Math.max(...indexes) : 0;
  console.log(last_row);
}

Source for this code

Can anyone explain to me how this function could be changed up a bit to search for the column instead of the row?

Make several configuration saves/loadings of rpivottable on R

The following code I found on an other post (I could link if anybody is interested) adds the saving option on the R rpivottable using flexdashboard. The saving is done through cookies.
I am trying to recreate it but having multiple saving options, basically have SAVE1, SAVE2,.. and being able to load the wanted save. I am unexperienced with JS so it is really hard to do anything.

---
title: "rpivottable_test"
output: html_document
---
knitr::opts_chunk$set(echo = FALSE)
# devtools::install_github("fraupflaume/rpivotTable")
library(rpivotTable)
data(mtcars)
names(mtcars)[10] <- "George.Dontas"

Save Current Configuration
Restore Previous Configuration


rpivotTable(mtcars,rows="George.Dontas", cols = c("cyl"), width = "90%", height = "40%",
            rendererOptions = list(
              c3 = list(legend = list(show = FALSE), 
                        data = list(labels = TRUE),
                        options = list(responsive = TRUE,
                                       maintainAspectRatio = FALSE),
                        size = list(width = "600",
                                    height = "500")),
              d3 = list(size = list(width = "500", height = "500")))) 

// save current state of the tables to my browser
setTimeout(function(){       //add the events first
  document.querySelector('a#saveBtn').addEventListener('click', savoring);
  document.querySelector('a#restoBtn').addEventListener('click', giveItBack);
  function savoring() {                             // function to save
    el = document.querySelectorAll('.rpivotTable');
    for(i=0; i < el.length; i++){
      elId = el[i].getAttribute("id");
      stringy = $('#' + elId).data("pivotUIOptions"); // collect rows/columns filters
      delete stringy['aggregators'];                 // remove the arbitrary
      delete stringy['renderers'];
      stringy2 = JSON.stringify(stringy);            // make it one key:value
      window.localStorage.setItem('table' + i, stringy2); // store it!
    }
  };
  function giveItBack() {                           // function to regurgitate
    el = document.querySelectorAll('.rpivotTable');
    console.log("working on the giver");
    ods = [...el[0].ownerDocument.scripts];         // make it an array
    for(j=0; j < el.length; j++){
      elId = el[j].getAttribute("id");
      where = ods.filter(function(ods){             // filter scripts for table data
        return ods.dataset['for'] === elId;
      })[0].innerHTML; 
      where2 = JSON.parse(where).x.data;            // WOOO HOO! I figured it out!!
      where3 = HTMLWidgets.dataframeToD3(where2);   // finally sheesh!!
      gimme = window.localStorage.getItem('table' + j); // get storage
      $('#' + elId).pivotUI(where3, JSON.parse(gimme), true, "en"); // put it back!
    }
  }
},100);

Chrome Extension

I am trying to create a chrome extension that once I click a certain button in my extension, it will highlight the current tab. However, I am having a little bit of trouble.

Right now I have
document.getElementById("button").addEventListener("click", function () {} in my JS file, but I can’t seem to find a solution on how to colour the current tab. I know something is supposed to go in {}, but I am not exactly sure what. Any help would be appreciated.

TypeScript / JS variable returning the entire self function

i´m new to TypeScript and I am facing this extremely awkward situation.

  1. The Beggining

First of all I declared a array of objs class prop name compras

constructor() {
  this.compras = [
    {id: 1, nome: 'Compra 1'},
    {id: 2, nome: 'Compra 2'},
    {id: 3, nome: 'Compra 3'},
    {id: 4, nome: 'Compra 4'},
  ]
}
  1. “Map the way”

Then I declared a function to get the bigger id and increment it by 1 (getting the next id) of this array of obj:

  _compras_next_id() {
    let biggerId = 0;

    this.compras.map(x => {
      biggerId = x.id;
    });

    console.log('bigger '+ biggerId)

    return biggerId + 1;
  }
  1. Trauma

Well, in my mind it should work fine, but when printing it… this is the result:

the problem

Webpack 5 – Scss relative urls won’t load images

I have my scss and my images in folders at the same level.

File structure

styles
  app.scss
images
  my-image.jpg

Am trying to import my image like so

app.scss

body {
  background: url(../my-image.jpg);
}

I have a simple webpack configuration to load scss and images.

webpack.config.js

{
  test: /.scss$/,
  use: [
    {
      loader: "style-loader",
    },
    {
      loader: "css-loader",
    },
    {
      loader: "sass-loader",
    },
  ],
},

Later on I tried to use resolve-url-loader between css-loader and scss-loader which seemed promising. But also to no avail.

The build isn’t throwing any errors. But the page doesn’t open the image.

Thank you for any help you give me my bros and bronettes.

While navigating HTML Elements with forEach, the getElementsByClassName function does not work on these elements

Let me try to explain, but you will understand better when you see the codes. I get my div elements with the getElementsByClassName function and then convert it to an array with the Array.from() function. While navigating this array with the forEach function, I am sending each element to a function. In this function, the item parameter represents my element. I can display this element with console.log(item) and even list its child elements with item.children. However, when I select this div with document.getElementById() using Inspect(F12) and then run the getElementsByClassName function only on this div, I do not get an error, but in the item.getElementsByClassName function I wrote in the html page, I get the error 'Uncaught TypeError: item.getELementsByClassName is not a function'.

I leave the code I wrote below. Error in registerClickOrdering function.

function registerClickHandler() {
          $('.remove_question_div').click(function() {
            var removedId = parseInt($(this).parent().attr('id').split('-').slice(-1))
            $(this).parent().remove();
            
            var questions = Array.from(document.getElementsByClassName('questions')).slice(removedId-1)
            console.log(questions)
            questions.forEach((item, index) => {registerClickOrdering(item, index)})
          });
        }

const registerClickOrdering = (item, index) => {
      console.log(item)
      item.id=`question_div-${index+2}`
      var questionCounterLbl = item.getELementsByClassName('question-counter')[0]
      questionCounterLbl.textContent = `${index+1}. Soru`
      var questionTitle = item.getELementsByClassName('question-title')[0]
      questionTitle.name = `question-${index+1}`
      questionTitle.id = `id_question-${index+1}`
      var answerInputs = Array.from(item.getELementsByClassName('answers-input'))
      answerInputs.forEach((item) => {
        item.name = `answer-${index+1}`
      })

    }

cypress returning “undefined” argument when using fixture and POM

after fixing some issues with my fixtures I am playing around with cypress scripts using POM but whenever I want my function to type some data I have in my JSON file I get the following message

cy.type() can only accept a string or number. You passed in: undefined

Here is my code, I made sure to follow correct instructions on how to use the fixtures

import loginPage from '../POM/pomtest.js'

const credentials = require('../../fixtures/loginTestCases.json')

/// <reference types= "cypress" />
describe("test suite", function(){
    let credentials;

    before(() => {
        cy.fixture('loginFixture').then((logindata) =>{
            credentials = logindata;
            return credentials
        });
    })

    beforeEach(() =>{
        loginPage.visit();
        cy.wrap(credentials).as('credentials')
    })

    it('incorrect username', function (){
        loginPage.clickLoginBtn()
        loginPage.typeUsername(this.credentials.usernameIncorrecto);
        loginPage.typePassword(this.credentials.passwordCorrecto);
        loginPage.clickLoginBtn();
        loginPage.elements.myNotes().should('have.text', this.credentials.loginFallido);
    })

    it('incorrect password', function (){
        loginPage.clickLoginBtn()
        loginPage.typeUsername(this.credentials.usernameCorrecto);
        loginPage.typePassword(this.credentials.passwordIncorrecto)
        loginPage.clickLoginBtn()
        loginPage.elements.myNotes().should('have.text', this.credentials.loginFallido)
    })

    it('Valid Login', function (){
        loginPage.clickLoginBtn()
        loginPage.typeUsername(this.credentials.usernameCorrecto);
        loginPage.typePassword(this.credentials.passwordCorrecto)
        loginPage.clickLoginBtn()
        loginPage.elements.myNotes().should('have.text', this.credentials.loginCorrecto)
    })
})

And here is my POM file

class loginPage{
    elements = {
        usernameInput: () => cy.xpath("//input[@placeholder='Username']"),
        passwordInput: () => cy.xpath("//input[@name='login.password']"),
        loginBtn: () => cy.get('button').contains('Login'),
        errorMsg: () => cy.get('#login-error-message'),
        myNotes: () => cy.get('H2')
    }

    typeUsername(username){
        this.elements.usernameInput().type(username);
    }

    typePassword(password){
        this.elements.passwordInput().type(password);
    }

    clickLoginBtn(){
        this.elements.loginBtn().click();
    }

    visit(){
        cy.visit("http://testapp.galenframework.com/")
    }

    fillemail(value){
        let field = cy.xpath("//input[@placeholder='Username']")
        field.clear()
        field.type(value)
    }

    fillpassword(value){
        let field = cy.xpath("//input[@name='login.password']")
        field.clear()
        field.type(value)
    }
}
//export default loginPage
module.exports = new loginPage();

I am getting errors when trying to type what’s on my JSON file

[{
  "name": "Usuario incorrecto",
  "username": "[email protected]",
  "password": "test123",
  "message": "The username or password are incorrect"
},
{
  "name": "password incorrecta",
  "username": "[email protected]",
  "password": "incorrecta",
  "message": "The username or password are incorrect"
},
{
  "name": "login exitoso",
  "username": "[email protected]",
  "password": "test123",
  "message": "My Notes"
}
]

group all numbers with slashes using regex

hey i wonder to group all the numbers include the slashes

i have strings like this

  1. some text 156/6
  2. other text 54/966
  3. another text 1/9

and so on ..

i want to group this from the results
i mean the numbers include the slashes

like this 156/6
54/966
1/9

i tried this but its not working if i add and letter txt before or after the numbers with slashes

^d+(/d+)*$

Is it possible to use the File System Access API to watch a file?

I am working on a chrome extension that will prompt a user for a directory and then will upload specific files from that directory to the site that the extension is active on. Ideally, this extension would automatically upload these files when they change on the user’s drive. With the File System Access API, I can setup a system where I can poll the contents of the file to see if they’ve changed:

const handles = {
  translation:{handle:null,text:''},
  html:{handle:null,text:''},
  css:{handle:null,text:''}
};
//updateDirectory is triggered by clicking on a "select directory" button
async function updateDirectory(){
  const directoryHandle = await window.showDirectoryPicker();
  Object.keys(handles).forEach((key)=>handles[key] = null);//Clear the preexisting handles.
  //Get the handles for the individual files/directories
  if(handles.interval){
    clearInterval(handles.interval);
  }
  for await (let handle of directoryHandle.values()){
    if(handle.kind === 'file'){
      console.log('handle.name:',handle.name);
      if(handle.name === 'translation.json'){
        handles.translation.handle = handle;
      }else if(handle.name.endsWith('.html')){
        handles.html.handle = handle;
      }else if(handle.name.endsWith('.css')){
        handles.css.handle = handle;
      }
    }
  }
  startFilePoll();
}

function startFilePoll(){
  handles.interval = setInterval(updateSheet,5000);//Check files every 5 seconds
}

async function updateSheet(){
  const filePromises = Object.entries(handles).map(async ([fileType,handle])=>{
    const file = await handle.getFile();
    const text = await file.text();
    if(text !== handles[fileType].text){
      //upload file changes
    }
  });
  await Promise.all(filePromises);
  //Do other things with the changed files.
}

Is there a watch() method buried in the API documentation that I just haven’t found, or some other way for the extension to monitor the file states without needing to constantly poll.

React router dom, Navigate with Outlet

Trying to setup boiler plate for user authentication with react. Currently my code allows for if loggedIn: true and if you are at / you can see all the content you are supposed to. Then if you change loggedIn: false it will redirect you to the sign in page /signin. However if you are at the sign in page and loggedIn is changed to true from false, loggedIn : true you stay on /signin unless you manually change that.

protectedRoutes.js:

const useAuth = () => {
    const user = { loggedIn: true }
    return user && user.loggedIn;
}

const ProtectedRoutes = () => {
    const isAuth = useAuth()
    return isAuth ? <Outlet /> : <Navigate to="/signin" />;
}

export default ProtectedRoutes;

app.js

export default function App() {
  return (
    <div>
      <Routes>
        <Route path='/signin' element={ <Signin />} />
        <Route element={<ProtectedRoutes />}>
          <Route path='/' element={ <Main />} />
        </Route>
        
       
      </Routes>
      
    </div>
  )
}

The way I tried solving this was:

const useAuth = () => {
    const user = { loggedIn: true }
    return user && user.loggedIn;
}

const ProtectedRoutes = () => {
    const isAuth = useAuth()
    return isAuth ? <Outlet /> && <Navigate to='/' /> : <Navigate to="/signin" />;
}

export default ProtectedRoutes;

This way however just results in an infinite loop : react-dom.development.js:86 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. I understand now why it is infinite looping, just unsure if there is a shorthand to write what I am trying to do.

i need help whit inputs in pysript

but does anyone know how to make an input work as such, for example I am making a chatbot with this pyscript method and I have this simple problem, I cannot make the entered text be saved in the variable to do this process, I am new to this and it would help me, here in the python code fragment you can see a def with the name get_response(user_input) that method is the one that is in charge of generating everything but it gives me an error when executing it since the “user_input” does not has no data entered is the only error I have and I don’t know how to fix it so I can read it in html

def get_response(user_input):
split_message = re.split(r's|[,:;.?!-_]s*', user_input.lower())
response = check_all_messages(split_message)
return response