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.

Selecting a single input value from an HTML file using only javascript

I am trying to do a form validation WITHOUT jquery. I have found this code, but I am not sure how to convert it from Jquery to plain Javascript.
I found this code here

$('.clickme').click(function() {

  alert($(this).prev().val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="bbb" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="ccc" />
<input type="button" class="clickme" value="Get Value" />


<input type="hidden" name="myvalue" class="form-control input_text" value="ddd" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="eee" />
<input type="button" class="clickme" value="Get Value" />

Any help with this would be amazing. I have multiple forms in one HTML file, all with the same input variables, and I need the functions to only run for when that specific input button is clicked.

Destructuring Class methods loses (this) context [duplicate]

i’m wondering if it’s possible to destructure the properties/methods from an instance of a class or function while maintaining scope across the destructured variables without having to use call() every time i need that method? For example:

class Pearson {}

Pearson.prototype.speak = function speak(){
  return this.sayHi
};

Pearson.prototype.speakOutLoud = function speakOutLoud(){
  return this.speak().toUpperCase()
};

const pearson = Object.assign(new Pearson(), {sayHi:"hi!!"});

const {speak, speakOutLoud} = pearson;

speak.call(pearson) // hi!!
speakOutLoud.call(pearson) // HI!!

I want to avoid the call() because i have a bunch of methods, and i want to know if exist any cleaver solution to this.