AgGrid access grid data in a CustomRowRenderer

I am using a AGGrid (actually via custom wrapper) and I have checkoboxes on each row.
Also, I have a bottom row with buttons. I want to enable/disable the buttons based on selected rows.

<AgGrid
                        id="dataListGrid"
                        containerProps={{style: {height: gridData.length * 30, minHeight: 180}}}
                        className="customGrid"
                        columnDefs={dataListColumns}
                        frameworkComponents={{checkboxColRenderer: checkboxColRenderer}}
                        gridDescription="List"
                        onGridReady={handleGridReady}
                        rowData={gridData}
                        enableBrowserTooltips={true}
                        pagination
                        paginationPageSize={100}
                        onCellClicked={onCellClicked}
                        onRowSelected={(params) => {
                              params.api.redrawRows({
                                rowNodes: [params.api.getPinnedBottomRow(0)],
                              });
                            }}
                        isFullWidthCell={(rowNode) => rowNode.rowPinned === 'bottom'}
                        fullWidthCellRenderer={CustomPinnedRowRenderer}
                        pinnedBottomRowData={[{}]}
                        {...props}
                    />   

My data looks like below;

let gridData = [{
            fmIdentifier: 'Test data 1',
            category: 'Test',
            comments: 'Test',
            fm: 'Test',
            gti: 'Test data',
            wins: 'Test',
            identifier: 'Test',
            status: 'Test data',
        }, {
            fmIdentifier: 'Test data 2',
            category: 'Test',
            comments: 'Test',
            fm: 'Test',
            gti: 'Test data',
            wins: 'Test',
            identifier: 'Test',
            status: 'Test data X',
            rowPinned: 'bottom'
        }]
        setDataListColumns(DataListColumns);
        setGridData(gridData);

Below is how my CustomPinnedRowRenderer looks;

class CustomPinnedRowRenderer {
  init(params) {
    this.eGui = document.createElement('div');
// QUESTION : I want to access the grid data here...param.api.data shows empty object {}
    const selectedNodes = params.api.getSelectedNodes();
    this.eGui.innerHTML = finalDOMStr; //finalDOMStr has HTML

  }

  getGui() {
    return this.eGui;
  }

  refresh() {
    return false;
  }
}

My question is inside the CustomPinnedRowRenderer (on row select), I want to check the param.api.data (so that I can accordingly render enabled/disabled buttons)

But param.api.data seems to be empty object for some reason ?

Javascript: Dynamic Image creation

I want to upload multiple images and display them on the webpage. Following is the code which I have done ->

let fileInput = document.getElementById("file-input");
let imageContainer = document.getElementById("images-space");
let numOfFiles = document.getElementById("num-of-files");

function preview(){
    imageContainer.innerHTML = "";
    numOfFiles.textContent = `${fileInput.files.length} Files Selected`;
    $("#images_2nd_div_heading").html('<p><b>You have Selected ' + 
   `${fileInput.files.length}` + ' Images.</b> (Click on the images to add Tags)</p>');
    var count = 1;
    var html2='';
    for(i of fileInput.files){
        let reader = new FileReader();
        let figure = document.createElement("figure");
        let figCap = document.createElement("figcaption");
        figCap.innerText = i.name;
        figure.appendChild(figCap);
        reader.onload=()=>{
            let img = document.createElement("img");
            img.setAttribute("src",reader.result);
            img.setAttribute("name","img"+count);
            figure.insertBefore(img,figCap);
        }
        imageContainer.appendChild(figure);
        reader.readAsDataURL(i);
    }

Now the images are loaded perfectly on the webpage. The only problem being that the img.setAttribute used for name is setting "name":img4 if I select 3 Images from the webpage.

I don’t know why it is happening .

Here is the HTML code ->

<div class="container1">
            <input type="file" id="file-input" name="file" accept="image/png, image/jpeg" onchange="preview()" oninput="this.className = ''" multiple>
            <label for="file-input">
              <i class="fa fa-upload choose_photo"></i> &nbsp; Choose Your Photos
            </label>
            <p id="num-of-files">
              No Files Chosen
            </p>
            <div id="images-space"></div>
          </div>
        </div>

Validate HTML forms using JavaScript

I challenged my self to create a simple html form using JavaScript yet I’m not sure if what I’m coding is right. I’m still a beginner in this language I hope someone could clarify me from my mistakes.

Input fields listed below and use JavaScript to validate them (use an internal declaration):

  1. Name: Any input will be accepted. Must be required.
  2. Birthday: Only 18 years and up only. Must be required.
  3. Email Address: Gmail are only accepted. Must be required.
  4. Email Address Confirmation: Email Address input must match. Must be required.
  5. Password: At least one capital letter, one number, and one special character must be included in the password. A total of eight characters are required.
  6. Password Confirmation: Password input must match. Must be required.

This is my code:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div class="container">
   <!-- Input Name -->
  <form action="submitted.html">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <br><br>

    <!-- Input Email -->
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" pattern="[a-z0-9._%+-][email protected]" title="Email must only be from Gmail" required>
    <br><br>

    <!-- Input Confirm Email -->
    <label for="ConfirmEmail">Confirm Email:</label>
    <input type="email" id="ConfirmEmail" name="ConfirmEmail" pattern="[a-z0-9._%+-][email protected]" title="Email must only be from Gmail" required>
    <br><br>
    
    <!-- Input Password -->
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" pattern="^(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,8}$" title="Password must have at least 1 Capital Letter, 1 Number, and 1 special character. Must have a total of 8 characters." required>
    <br><br>

    <!-- Input Confirm Password -->
    <label for="confirmPassword">Confirm Password:</label>
    <input type="password" id="confirmPassword" name="confirmPassword" pattern="^(?=.*[0-9])(?=.*[A-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,8}$" title="Input must be the same with password." required>
    <br><br>

    <!-- Submit Button -->
    <input type="submit" value="Submit">
  </form>
</div>
                
<script>
var myEmail = document.getElementById("email");
var myConfirmEmail = document.getElementById("confirmEmail");
var myPassword = document.getElementById("password");
var myConfirmPassword = document.getElementById("confirmPassword");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var special = document.getElementById("special");
var length = document.getElementById("length");

myEmail.onkeyup = function(){
  // Email: Confirm
  function matchEmail(){
  if(myEmail != myConfirmEmail){   
    myConfirmEmail.classList.remove("invalid");
    myConfirmEmail.classList.add("valid");  
  }else{  
    myConfirmEmail.classList.remove("valid");
    myConfirmEmail.classList.add("invalid"); 
  }  
}  

}

// When the user starts to input there is a pop-up text or validation reminder
myPassword.onkeyup = function(){

  // Password: Validate capital letters
  var capital = /[A-Z]/g;
  if(myPassword.value.match(capital)){  
    capital.classList.remove("invalid");
    capital.classList.add("valid");
  }else{
    capital.classList.remove("valid");
    capital.classList.add("invalid");
  }

  // Password: Validate numbers
  var numbers = /[0-9]/g;
  if(myPassword.value.match(numbers)){  
    number.classList.remove("invalid");
    number.classList.add("valid");
  }else{
    number.classList.remove("valid");
    number.classList.add("invalid");
  }

  // Password: Validate special characters
  var special = /(?=.*[!@#$%^&*])/g;
  if(myPassword.value.match(special)){  
    special.classList.remove("invalid");
    special.classList.add("valid");
  }else{
    special.classList.remove("valid");
    special.classList.add("invalid");
  }

  // Password: Validate length exactly 8 characters
  if(myPassword.value.length == 8){
    length.classList.remove("invalid");
    length.classList.add("valid");
  }else{
    length.classList.remove("valid");
    length.classList.add("invalid");
  }

  // Password: Confirm
  function matchPassword(){  
  var pw1 = document.getElementById("myPassword");  
  var pw2 = document.getElementById("myConfirmPassword");  
  if(pw1 != pw2){   
    myConfirmPassword.classList.remove("invalid");
    myConfirmPassword.classList.add("valid");  
  }else{  
    myConfirmPassword.classList.remove("valid");
    myConfirmPassword.classList.add("invalid"); 
  }  
}   

}
</script>

</body>
</html>

I still haven’t finish it because I was stuck at the email address confirmation. Thank You!

Fetching data from firestore does not immediately shows data if I render the data using my searchList

I have this data where I fetch all of the products in Firestore:

const [products, setProducts] = useState([]);
  useEffect(() => {
    let isMounted = true;

    const getProducts = async () => {
      const querySnapshot = await getDocs(collection(db, "products"));
      const arr = [];
      querySnapshot.forEach((doc) => {
        arr.push({
          ...doc.data(),
          id: doc.id,
        });
      });
      if (isMounted) {
        setProducts(arr);
        setIsLoading(true);
      }
    };

    getProducts().catch((err) => {
      if (!isMounted) return;
      console.error("failed to fetch data", err);
    });

    return () => {
      isMounted = false;
    };
  }, []);

Example data of the product:

enter image description here

I also have this searcList so users can search any of the products, sizes, or categories. The problem here is that it does not immediately shows the data of the products once it is mounted. I have to first type in a specific product and it will display the specific item, and when I click x to clear the search field that is the time it will display all of the products. However, if I change the searcList.map to productList.map, it will immediately render the products

 const [searchList, setSearchList] = useState([]);
  const [searchKey, setSearchKey] = useState("");

  useEffect(() => {
    let x = [...products];
    x = x.filter((y) => {
      const key = searchKey.toLocaleLowerCase();
      const values = ["prodName", "size", "cat"];
      return values.some((val) => y[val].toLocaleLowerCase().includes(key));
    });
    setSearchList(x);
  }, [searchKey]);

  const handleClear = () => {
    console.log("clear");
    setSearchKey("");
  };

Displaying the searchList with a map:

{searchList.map((item, index) => (
          <List key={index}>
            <Paper>
              <ListItemText
                primary={item.prodName}
                secondary={
                  item.size + "(Size)" + "  -  " + item.cat + "(Category)"
                }
              />
                  <br />
                </div>
              ))}
            </Paper>
          </List>
        ))}

Browser XSLT, any way to get back to the original XML?

Say you have a source XML file with ?xml-stylesheet PI, so when you load it into a browser it will be transformed through the stylesheet. Let’s say the source XML file was transformed to HTML and is displayed. All good.

Now the HTML contains a script (javascript) element to do stuff. Is there any way, standard or secret, by which one could get back to the original source XML of the current document?

I did not find one, so I have the XSLT output the source into a head/script element with id=”source” and type=”text/xml”. But when I load that with

document.getElementById("source").firstChild 

I get text not the actual element. If I do DOMParser parseFromString, I get a namespace prefix undeclared error, because XSLT didn’t output the namespace prefixes that were already declared under this source node.

Perhaps there is some way with a different HTML element that it actually reads the content as DOM nodes, with all the namespaces, not as a mere text node.

I have tried to use other elements than script, for example, there is a tag called <xml> in HTML, which you can use to embed XML. And when I use this, the

document.getElementById("source").firstChild 

actually gets me an element, not just a text node.

However that element is not namespace aware, so it does not know anything about the xmlns declaration that were already made outside and the XSLT thus did not output again.

Ideally I could just get to the source XML without having to embed it in the HTML. But if I have to embed it, how can I force all namespaces to be declared again?

How to make the content slide smoothly together with the sidebar?[react]

When my sidebar transitions to width: 0, the content right next to it (on its right) doesn’t slide with it. It’s like the text waits for the sidebar to be done with its animation before it takes the sidebar’s place, even though I set its transition as well.

I came up with a minimal reproducible example below:

//Sidebar.js
import './styles/Sidebar.css'

export const Sidebar = () => {
  const [show, setShow] = useState(false);
  
  const toggle = ()=>{
    setShow(!show);
}

  return (
    <div>
        <div id={'toggle-btn'}>
            <button type='button' className='toggle-btn' onClick={toggle}>
                toggle
            </button>
        </div>
        <div style={{display:"flex"}}>
            <aside className={'sidebar' + (show ? ' showSidebar':'')}>
                <ul className='menuList'>
                    <li>Perfil</li>
                    <li>Estatísticas</li>
                    <li>Adicionar Itens</li>
                    <li>Procurar</li>
                </ul>
            </aside>
        </div>
    </div>
  )
}

/*Sidebar.css*/
.sidebar {
    width:100%;
    overflow: hidden;
    box-shadow: 0 8px 8px -4px ;
    transform: translateX(0);
    transition:all 1s ease;
    height:100vh;
}
.showSidebar {
    width:0;
}

//Dashboard.js
    import './styles/Dashboard.css'
    export const Dashboard = () => {
      return (
        <div className='dashboard'>
        <p>
        LORE IPSUM BLA BLA
        </p>
       </div>
      )
    }

/*Dashboard.css*/
.dashboard {
    max-width: 30%;
    margin-top:10rem;
    transition:all 1s ease;
}

//App.js
function App() {

  return (
    <div style={{display:"flex"}}>
    <Sidebar />
    <Dashboard /> 
    </div>
  );
}

export default App;

Change property state to false depending on value of another property Mongoose Express NodeJS

I need to change the status of a property from true to false depending on whether in the property called “outstandingBalance” its value is equal to 0. For now I receive the data to make the change of “outstandingBalance” correctly but I would like it to be evaluated if its value it goes to 0 to be able to make the change automatically.

This is my code:

    const previousBalance = parseFloat(lastPayment.previousBalance);
      
    const newAmount = parseFloat(data.adjustmentAmount);

    let newOutstandingBalance = 0;

    newOutstandingBalance = parseFloat(previousBalance) + parseFloat(newAmount);  

    const updateOutstandingBalanceSale = await Sale.findOneAndUpdate( {'_id': req.creditSaleToAdjust.saleId },{
        $set: {
            'outstandingBalance': newOutstandingBalance                                        
            },
    });

In my model I have the status property that I need to change if outstandingBalance has the value of 0

My model:

const SaleSchema = Schema (
  {
    saleId: {
        type: Number,
        unique: true
    },
    user:{
          type: Schema.Types.ObjectId,
          ref:'Users',
          required: [true, 'El Usuario es obligatorio']
    },
    clientId:{
        type: Schema.Types.ObjectId,
        ref:'Client',
        required: [true, 'El Cliente es obligatorio']
    },
    notes: {
        type: String,
        maxlength:200,
    },
    subtotal: {
        type: Number,
        default: 0,
        required: [true, 'El Subtotal es obligatorio']
    },
    discount: {
        type: Number,
        default:0
    },
    tax: {
        type: Number,
        default:0
    },
    totalBeforeTax: {
        type: Number,
        default: 0,
        required: [true, 'El Total sin Impuestos es obligatorio']
    },
    total: {
        type: Number,
        default: 0,
        required: [true, 'El Total es obligatorio']
    },
    paymentType: {
        type: String,
        required: true,
        enum: ['CASH', 'CREDIT', 'TRANSFER'] 
    },
    outstandingBalance: {
        type: Number,
        default: 0,
        required: [true, 'El Adeudo Pendiente es obligatorio']
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    status: {
        type: Boolean,
        default: true,
        required: [true, 'El Estatus es obligatorio']
    }
  }  
);

Thanks for your help.

How to extract data from Promise result and save to variable outside the function in javascript [duplicate]

The console log result is as follows:

(3) [Promise, Promise, Promise]
0: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "urn:adsk.wipprod:fs.folder:co.uqbu12FFQZO6y7GxUs7cKA"
1: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "urn:adsk.wipprod:fs.folder:co.uqbu12FFQZO6y7GxUs7cKA"
2: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "urn:adsk.wipprod:fs.folder:co.uqbu12FFQZO6y7GxUs7cKA"

I am trying the following to extract the data [[PromiseResult]] form the array,
with the following code:

   const final_results = [];
        for (const vals in final_vals) {
          // const temp = Promise.all(vals).then(function (values) {
          //   final_results.push(values.result);
          // });

          const temp = Object.values(vals);
          final_results.push(temp);
        }
        console.log(final_results);

I am trying to get the output with the results as an Array with the following values:

[“urn:adsk.wipprod:fs.folder:co.uqbu12FFQZO6y7GxUs7cKA”,”urn:adsk.wipprod:fs.folder:co.uqbu12FFQZO6y7GxUs7cKA”,”urn:adsk.wipprod:fs.folder:co.uqbu12FFQZO6y7GxUs7cKA”]

Vue Axios post timeout not effect

This is my function define, set timeout 1000 * 60 * 5 can’t effect, but request is working.

export function cmdActiveVsi (data) {
  return Vue.prototype.$api.post(baseUrl + '/com/mpls/v1/execVsiConfig', data, 1000 * 60 * 5)
}

This is Interceptors config, This config timeout is effect.

let instance = axios.create({
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  timeout: 1000 * 60
})

How can I stop create react app fast refresh on change to only act on save?

I’m not sure how can I make Fast_Refresh only activate the compilation on save rather than on any change made to source, as I’m typing;

at the moment its activated on any change without even needing a file save, and thats a little annoying for some large components, as I’m making a change it breaks the interface.
I thouhgt it’s watching filesystem, but something else is triggering the compilation as I’m typing…

I am using vscode, react project + typescript created using create-react-app using react “^17.0.2” on a large scale project.

forloop.counter0 in my django template is not working under original for loop

I have a for loop that goes through a list of inspections. I’d like to manipulate the things inside the tag depending on different situations. For test, I tried to using jquery to print out the id of the element as it iterates, but the forloop seems to be stuck at 0. when I put inside the html it will iterate, but when I put inside the attribute ‘id’, it will not iterate. based on the code below, it should iterate as many times as there is i in inspections. but it wont. I also tried to get a console.log() fo the innerHTML of my but all I get is the first item repeated over and over instead of going down the list (on the webage however it looks lile it iterated ok, just not on the backend I guess?).
note that jquery was imported at the beginning of the html. this is just snippet of issue.

I’d appreciate any help.

my code:

<div class="tab-pane fade" id="nav-inspection" role="tabpanel"
                                 aria-labelledby="nav-inspection-tab">
                                <div class="container"></br></br>
                                    {% for i in inspections %}
                                        <div class="card - mb-3" style="width: 40 rem;">
                                            <div class="card-body">
                                                <h3 class="card-title">{{i.Title}} - <span title="" id="s{{forloop.counter0}}">{{i.Condition}}</span>
                                                </h3>
                                                <script type="text/javascript">
                                                    console.log(document.querySelector('[title]').innerHTML);
                                                    $(document).ready(function(){
                                                        alert($('[title]').attr("id"));
                                                    });
                                                </script>
                                                <p>{{i.Desc}}</p>
                                                <h4><span class="badge badge-primary">{{i.Cost}}</span></h4>
                                            </div>
                                        </div>
                                    {% endfor %}
                                </div>
                            </div>

My dispatch function works but is not updating redux state

I understand that this question has been asked several times but my example doesn’t suffer from any of the solutions provided in the other examples. I hope someone can help, thanks in advance.

Here’s my slice, screenSlice.js:

import { createSlice } from '@reduxjs/toolkit';

//this slice sets the state of the screens Y axis
export const screenSlice = createSlice({
  name: 'screenYPlacement',
  initialState: {
    offsetY: 0,
  },
  reducers: {
    setoffsetY: (state, action) => {
      return {
        ...state,
        offsetY : action.payload
      }
    }
  }
});

export const { setoffsetY } = screenSlice.actions
export default screenSlice.reducer 

My store, store.js :

import { configureStore } from '@reduxjs/toolkit';
import screenReducer from './screenSlice';

export default configureStore({
  reducer: {
    offsetY: screenReducer
  },
});

The file in which it is called, app.js:

import React, { useEffect} from 'react'

import './App.scss';

import { useDispatch } from 'react-redux';
import { setoffsetY } from './redux/screenSlice';

import Header from './components/header/Header';
import Hero from './components/hero/Hero';

function App() {
  const dispatch = useDispatch()
  //this function will use the redux reducer to save the Y axis to redux
  const handleScroll = () => dispatch(setoffsetY(window.pageYOffset));
  
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  });

  return (
    <div className="App">
      <Header/>
      <Hero/>
    </div>
  );
}

export default App;

Axios get request status 503 if i call it inside a for loop

I want to make ten api calls to populate an array. If i make the same api call but outside of the for loop i don’t get any problem. But doing it inside the for loop i get some succesfull requests and a ton with a 503 status code, service unavaiable.

Here is my js:

function generatePersonJson() {
  const promise = axios.get(url, {
    headers: {
      Accept: "application/json",
      "User-Agent": "axios 0.21.1",
    },
  });
  const dataPromise = promise.then((response) => response.data);
  return dataPromise;
}

const createPerson = async () => {
  generatePersonJson()
    .then((data) => {
      if (data) {
        return data
      }
    })
    .catch((err) => console.log(err));
};

const createPersons = async () => {
  let personsArray = [];
  for (let i = 0; i < 11; i++) {
    const dev = await createPerson();
    personsArray.push(dev);
  }
  console.log(personsArray);
};

createPersons();

I get the error in the catch block inside the createPerson and it looks like this: response: { status: 503, statusText: 'Service Unavailable',

How do I make algolia search work with kitsu’s anime content api — using the index/indices and key/s provided by kitsu?

I cant seem to figure out how to connect algolia/algoliasearch to kitsu api: https://hummingbird-me.github.io/api-docs/#tag/Algolia

I was able to do the OAuth part. I am now trying to connect it to algolia.

Per kitsu:

Kitsu uses Algolia for searching. Algolia’s search provides more accurate search results and allows you to build complex search filters to find exactly what you want.

And as per the documentation I need to retrieve the keys and indices that I will use to connect to algolia:

All Algolia Keys – Get all the Algolia Keys needed to search Kitsu with Algolia.

So I was able to that as well — I had to fetch it from kitsu:

fetch('https://kitsu.io/api/edge/algolia-keys')
    .then(res => res.json())
    .then(data => console.log(data))

screenshot of the keys / indices

I have tried creating an account with algolia. I found tutorials but all of them would just create their own index and import dummy JSON data.

I was able to do this (create a new empty index from scratch):

https://github.com/algolia-samples/api-clients-quickstarts/blob/master/javascript/simple.js

…but it is still not giving any hint or example how to consume or use an external key or index that is not from my own algolia account. I just need to use the index and key that i got from that GET request from kitsu so that i can implement search using algolia on kitsu’s anime content on the website im trying to build.