React search filter not rerendering correctly on MY computer only?

This is really weird and my instructor is confused as well. I copied some code from my classmate — it worked fine on his computer. But it doesn’t work on mine.

The issue is with a search filter.

onChange={(e) => {
          if(!e.target.value) return setTransactions(allTrans)
          console.log(e.target.value)
          let search = transactions.filter((element) => {
            return element.description.includes(e.target.value)
          })
          if (search.length>0) setTransactions(search)
        }}

the stateful variable “transactions” is used here:

{transactions.map((transaction) => {
          return <Transaction key={transaction.id} transaction={transaction}/>
        })}

We figured out the issue is in the rerender. My instructor deleted this code and pasted it back in and that FIXED IT. But then it got messed up again when I edited something else (in a different file). And now I can’t fixed it.

What would be the reason identical React code works on my classmate’s computer but not mine?

How do I make a button that, when clicked, displays data in node.js?

So I’ve created a button, along with a table that shows data from my database. However, I want that data to appear only when the button is clicked.enter image description here

`<button id="breakfast2">Breakfast</button>
 <table id="mealTableContainer2">
            <thead>
                <tr>
                    <th id="mealname">Meal Name</th>
                    <th id="mealcalories">Calories</th>
                    <th id="mealtype">Type of Meal</th>
                    
                </tr>
            </thead>

            <tbody id="mealContainer2"></tbody>
  </table>`

The only Javascript I currently have is for getting my database into that table, but I really only want it to appear when I click the breakfast button. I just can’t figure out how; if someone could explain it to me very simply, I’d be appreciate it a ton!

Async Await with Mocha + Axios TrobuleShooting

we are using mocha + nodejs + axios

Below is the piece of code i have , they are all in different file.

File 1 : IT block

   it('Perform Post Payment Actions', function () {
    postPaymentController.triggerPostPaymentActions(params);
  });

File 2 : Controller

module.exports.triggerPostPaymentActions = function (params) {
  const actions = params.postAuthActionId.split('-');  // // 'PARTIALREFUND, 50, SUCCESS - PARTIALREFUND, 50, FAIL

  Object.entries(actions).forEach(([, action]) => {
    const actionAsArray = action.split(','); // 'PARTIALREFUND, 50, SUCCESS 

    switch (actionAsArray[0]) {. // PARTIALREFUND
      case 'PARTIALREFUND':
        paymentsPartialRefundApi.submitPaymentsPartialRefundApi(actionAsArray, params);
        break;
      default:
        break;
    }
  });
};

File 3: Acutal API Call using axios


module.exports.submitPaymentsPartialRefundApi = async function (actionDetails, params) {

  const postOptions = {
    url: partialRefundApiUri,
    method: 'POST',
    headers: restHeaders,
    data: params.partialRefundRequest,
  };

  try {
    const response = await axios(postOptions);
    params.partialRefundResponse = response.data;
    process.env.PARTIALREFUNDRESPONSE = JSON.stringify(params.partialRefundResponse);
  } catch (err) {
    process.env.ERRORCODE = err;
    process.env.SCRIPT_STATUS = 'failure';
    process.env.PARTIALREFUNDRESPONSE = 'Partial Refund request Failed';
    throw err;
  }



};

PROBLEM :

When the control is passed to submitPaymentsPartialRefundApi , then it builds the request for axios but rather than waiting for the axios call , it takes the control back to the switch case. my expectation was that since i am using async await it will execute and wait till the axios call is completed but rather than completing the call it returns the control back to the switch statement and from the switch it goes back to the IT block. so i have 2 problems.
1 Its not waiting for the axios call to end
2 Its not running switch twice in loop , its goes back to IT block and then comes back.

Solutions Tried :

I already tried using promises for this , with and without timeout but still it did not worked.
Any help on this is appreciated.

calculator does not work properly on mobile devices

I’ve been trying to solve this for hours and I can’t.

The problem is when you try to erase the numbers entered.

You have to first select the two fields and enter the dollar amount in the third field. Then enter a value in the first field.

On the computer it works normally, but on some cell phones it is not working properly.

On some iphone using safary in the latest version it works. Already on some android devices with Google no. I didn’t check the browser version, but I tried it on newer and older phones. Some new ones give a problem and some don’t, as well as old ones.

This code was not developed by me, it is a little old and uses a template language called Freemarker. Don’t care too much about this language, it’s used to get data from the form and insert it into the html code.

There’s a link for you to access and test. This page contains two calculators, it is the first one that is giving problems. I’ll post a print of it.

URL: https://www.smiles.com.br/p123kby0ocxqaelzcgszc9x6hsmwt59wbrftzbr5ovtgngq7cy
Print: enter image description here

Code:

<#assign
moduloSimulador = simulador_cobranded_separator
itemSimulador = moduloSimulador.getChild("item_simulador_separator").getSiblings()
>

<#list itemSimulador as cur_item>
<#assign
imagemItem = cur_item.getChild("imagem_item").getData()
textoImportanteItem = cur_item.getChild("texto_importante_item").getData()
>
 <div data-simulador-mod021 class="canta-mod021-simulador">
  <div>
      <div>
      <#if imagemItem?has_content>
        <img src="${imagemItem}" alt="Imagem Simulador" />
      </#if>
          
      </div>
      <div>
          <div class="content-input">
              <label for="lblSeg">Assinante Clube Smiles</label>
              <select data-mod021-assinante id="lblSeg">
                  <option value="">Escolha</option>
                  <option value="sim">Sim</option>
                  <option value="nao">Não</option>
              </select>
          </div>
      </div>
      <div>
          <div class="content-input">
              <label for="lblCart">Tipo de Cartão</label>
              <select data-mod021-cartao id="lblCart">
                  <option value="">Escolha</option>
                  <option value="infinite">Infinite</option>
                  <option value="platinum">Platinum</option>
                  <option value="gold">Gold</option>
                  <option value="inter">Inter</option>
              </select>
          </div>
      </div>
      <div class="break-sm"></div>
      <div>
          <div class="content-input rs">
              <label for="lblValorGasto">Valor gasto no cartão</label>
              <input value="0" min="1" maxlength="12" data-mod021-valor class="style2" type="text" id="lblValorGasto" placeholder="0" />
          </div>
      </div>
      <div>
          <div class="content-input">
              <label for="lblConversor">Conversor</label>
              <input data-mod021-conversor readonly class="style2" type="text" id="lblConversor" placeholder="0" />
          </div>
      </div>
      <div>
          <div class="content-input rs">
              <label for="lblDolar">Cotação do Dólar</label>
              <input value="0" min="1" maxlength="5" data-mod021-cotacao class="style2" type="text" id="lblDolar" placeholder="0" />
          </div>
      </div>
      <div class="sep">=</div>
      <div>
          <div class="content-input">
              <label for="lblAcumulo">Acúmulo</label>
              <input data-mod021-acumulo readonly class="style2" type="text" id="lblAcumulo" placeholder="0" />
          </div>
      </div>
  </div>
  <p class="p-jur">
      ${textoImportanteItem}
  </p>
</div>
</#list>


<script>
(function(window) {
  "use strict";

  let $items = document.querySelectorAll("[data-simulador-mod021]");
  if ($items.length > 0) {
    for (let a = 0; a < $items.length; a++) {
      engine($items[a]);
    }
  }

  function isValidKey(key) {
    if (
      (key >= 49 && key <= 57) ||
      (key >= 97 && key <= 105) ||
      key == 8 ||
      ((key == 48 || key == 96) &&
        milesInput.value !== '' &&
        milesInput.value !== '0')
    ) {
      return true;
    }
  }

  //mascara de valor
  function mascaraValor(valor) {
    valor = valor.toString().replace(/D/g, "");
    valor = valor.toString().replace(/(d)(d{9})$/, "$1.$2");
    valor = valor.toString().replace(/(d)(d{6})$/, "$1.$2");
    valor = valor.toString().replace(/(d)(d{3})$/, "$1.$2");
    return valor;
  }

  function getValorMoneyBr(valor) {
    let value = valor
      .toFixed(2)
      .toString()
      .split(".");
    let formatFirstPart = mascaraValor(value[0]);
    let formatSecondPart = "," + value[1];

    let formatedValue = formatFirstPart + formatSecondPart;
    return formatedValue.toString();
  }

  //mascara de mordas
  function moeda(v) {
    v = v.toString().replace(/D/g, ""); //permite digitar apenas números
    v = v.toString().replace(/[0-9]{12}/, "inválido"); //limita pra máximo 999.999.999,99
    //v = v.toString().replace(/(d{1})(d{8})$/, "$1.$2"); //coloca ponto antes dos últimos 8 digitos
    //v = v.toString().replace(/(d{1})(d{1,2})$/, "$1.$2"); //coloca ponto antes dos últimos 5 digitos
    v = v.toString().replace(/(d{1})(d{1,2})$/g, "$1,$2"); //coloca virgula antes dos últimos 2 digitos
    return v.toString();
  }

  //define o valor do conversor
  function changeConversor(c, a) {
    let valueConversor = "";
    let cartao = c.value;
    let assinante = a.value;

    if (cartao && assinante) {
      if (cartao === "infinite") {
        if (assinante === "sim") {
          valueConversor = 4;
        } else {
          valueConversor = 2.2;
        }
      } else if (cartao === "platinum") {
        if (assinante === "sim") {
          valueConversor = 3;
        } else {
          valueConversor = 2;
        }
      } else if (cartao === "gold") {
        if (assinante === "sim") {
          valueConversor = 2.5;
        } else {
          valueConversor = 1.5;
        }
      } else {
        if (assinante === "sim") {
          valueConversor = 2;
        } else {
          valueConversor = 1.35;
        }
      }

      return valueConversor;
    } else return "";
  }

  function engine(item) {
    let assinante = item.querySelector("[data-mod021-assinante]");
    let cartao = item.querySelector("[data-mod021-cartao]");
    let valor = item.querySelector("[data-mod021-valor]");
    let conversor = item.querySelector("[data-mod021-conversor]");
    let cotacao = item.querySelector("[data-mod021-cotacao]");
    let acumulo = item.querySelector("[data-mod021-acumulo]");
    let conversorValor = "";

    function calc() {
      let nValor = valor.value.toString().replace(/(D)/g, "");

      let nCotacao = moeda(cotacao.value);

      nCotacao = nCotacao.replace(",", ".");

      nCotacao = parseFloat(nCotacao);

      let nConversor = parseFloat(conversor.value.toString().replace(",", "."));

      if (nValor <= 0 || nCotacao <= 0) {
        valor.value = "";
        cotacao.value = "";
        acumulo.value = "";
      } else {
        let v = (nValor / nCotacao) * nConversor;
        // acumulo.value = getValorMoneyBr(v);
        acumulo.value = Math.round(v);
      }
    }

    valor.addEventListener("keyup", function(event) {
      if(!event.keyCode) return;

      let v = this.value;
      valor.value = mascaraValor(v);

      if (valor.value && conversor.value && cotacao.value) {
        calc();
      }
    });

    cotacao.addEventListener("keyup", function() {
      if(!(event.keyCode)) return;

      if (valor.value && conversor.value && cotacao.value) {
        calc();
      }
    });

    cotacao.addEventListener("keyup", function() {
      if(!event.keyCode) return;

      let v = this.value;
      cotacao.value = moeda(v);
    });

    //define valor conversor
    if (assinante && cartao) {
      cartao.addEventListener("change", function() {
        conversorValor = changeConversor(cartao, assinante);
        conversor.value = conversorValor.toString().replace(".", ",");

        valor.value = "";
        cotacao.value = "";
        acumulo.value = "";
      });

      assinante.addEventListener("change", function() {
        conversorValor = changeConversor(cartao, assinante);
        conversor.value = conversorValor.toString().replace(".", ",");

        valor.value = "";
        cotacao.value = "";
        acumulo.value = "";
      });
    }
  }
})(window);
</script>

How do I pass mapped props to a component using useState?

I have a shopping cart component that I’ve passed a useState prop to update the number of items within the shopping cart / the amount of money that the cart is worth:

import { data } from "./data";

export default function StoreItems({ addToCart, Total, setTotal }) {
  const addToTotal = (data) => {
    addToCart();
    setTotal(Total + data.price);
  };
  return (
          <Grid container spacing={3}>
            {data.map((data) => (
              <Grid item key={data.id} xs={12} sm={6} md={3}>
                <Card>
                  <CardMedia
                    image={data.image}
                  />
                  <CardActions>
                    <div>
                      <Button>Buy</Button>
                      <Button
                        size="small"
                        sx={{ marginLeft: "5px" }}
                        onClick={addToTotal}
                      >
                        Add to Cart
                      </Button>
                    </div>
                  </CardActions>
                </Card>
              </Grid>
            ))}
          </Grid>
  );
}

The Data is a JavaScript object that looks like:

export const data = [
  {
    id: 1,
    title: "item 1",
    content: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac aliquam nunc. 
    Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.`,
    image: "https://source.unsplash.com/random/1",
    price: 5000,
  },
];

And the props are passed down from:

function Store() {
  const [cartCount, setCartCount] = useState(0);
  const [Total, setTotal] = useState(0);

  const addToCart = () => {
    setCartCount(cartCount + 1);
  };

  return (
    <>
      <div>
            <StoreItems
              Total={Total}
              setTotal={setTotal}
              addToCart={addToCart}
            />
      </div>
    </>
  );
}

export default Store;

Why is it that I am unable to add the price of data.price to the useState – Total object

Check/Uncheck checkbox depend on value match

How can we get a checkbox checked only if a dynamic value matches the checkbox value in one line without applying if condition. otherwise uncheck checkbox,.

var checkVal = 'red';
$('#black:input[value="'+checkVal+'"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-check">
  <input class="form-check-input" type="checkbox" value="black" id="black" checked>
  <label class="form-check-label" for="black">
    Black
  </label>
</div>

Image is not loading in app, but it loads when url is used in browser

I have an app in react which does not show the <img /> tag ( it shows a broken image ) inside the app. If I do make a request to the same url using postman or directly in the browser, I can see the image. The image is stored in wordpress. I have no more ideas on what to try.

Adding any code snippet is irelevant. I have tried a simple html page and it does NOT work.

trying do Sign In validation with fetch. and server return me null

I learning Full Stack , and have problem with HW..
The sign Up send all data to database great, But when I try find user from database (To sign In) its return me always null.
In database I have user with mail [email protected] and its not find him.
Without fetch its working great, But I need use fetch here (By the homework)
Tried find some fetch sign in tutorial, but its not help.

[1]
[2]
[3]
[1]: https://i.stack.imgur.com/XIdfF.png
[2]: https://i.stack.imgur.com/x1Sz4.png
[3]: https://i.stack.imgur.com/bBMh9.png

TypeError: _this.provider is not a function

I’m trying to use microsoft-graph-client api to get user data. I’m using nodejs and javascript I was able to login using graph api but unable to get user data. You can check the code from this blogs

to get user data:
https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=javascript

to get authClient value:
https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=Javascript#authorization-code-provider

Here’s the full error:
TypeError: _this.provider is not a function

at C:….CustomAuthenticationProvider.js:43:31

at new Promise ()

at CustomAuthenticationProvider. (C:….CustomAuthenticationProvider.js:42:39)

at step (C:….node_modulestslibtslib.js:143:27)

at Object.next (C:….node_modulestslibtslib.js:124:57)

at C:….node_modulestslibtslib.js:117:75

at new Promise ()

at __awaiter (C:…..node_modulestslibtslib.js:113:16)

at CustomAuthenticationProvider.getAccessToken (C:….node_modules@microsoftmicrosoft-graph-clientlibsrcCustomAuthenticationProvider.js:39:3

at AuthenticationHandler. (C:…node_modules@microsoftmicrosoft-graph-clientlibsrcmiddlewareAuthenticationHandler.js:62:69)

{
statusCode: -1,
code: ‘TypeError’,
requestId: null,
body: ‘TypeError: _this.provider is not a function’
}

get exact location with tag manager

Is it possible to get exact location(latitude/longitude) from Google Tag Manager, when user from android device view web page?

Ideally, I would be able to set-up this up in GTM. If it is possible, can someone please explain how to do it?

Thanks so much!

Element type is invalid: expected a string but got undefined, check the render method of `AnimatedComponent` – ReactNavigation

I’m stucking a couple of days with ReactNavigation v6+, also there are several similar questions/answers about the invalid element type, but none of them is working with this simple example:

The issue was started after adding the material-top-tap navigation from @react-navigation module.

To avoid complexity, I use the minimal needed code lines to reproduce this error:

import React from 'react';
import {View, Text} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';

const TopBarOne = () => (
  <View>
    <Text>TOP BAR ONE</Text>
  </View>
);
const TopBarTwo = () => (
  <View>
    <Text>TOP BAR TWO</Text>
  </View>
);

const TopTabBar = createMaterialTopTabNavigator();

const TopBarStack = () => {
  return (
    <TopTabBar.Navigator>
      <TopTabBar.Screen name={'one'} component={TopBarOne} />
      <TopTabBar.Screen name={'two'} component={TopBarTwo} />
    </TopTabBar.Navigator>
  );
};

const NavigationProvider = () => {
  return (
    <NavigationContainer>
      <TopBarStack />
    </NavigationContainer>
  );
};

export default NavigationProvider;

The complete error log:


ERROR  Error: Element type is invalid: expected a string (for built-in components) or a
class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in,
 or you might have mixed up default and named imports.

Check the render method of `AnimatedComponent`.

This error is located at:
    in AnimatedComponent (at createAnimatedComponent.js:264)
    in AnimatedComponentWrapper (at PagerViewAdapter.tsx:123)
    in PagerViewAdapter (at TabView.tsx:79)
    in RCTView (at View.js:32)
    in View (at TabView.tsx:78)
    in TabView (at MaterialTopTabView.tsx:47)
    in MaterialTopTabView (at createMaterialTopTabNavigator.tsx:136)
    in Unknown (at createMaterialTopTabNavigator.tsx:135)
    in MaterialTopTabNavigator (at testProvider.tsx:23)
    in TopBarStack (at testProvider.tsx:33)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:430)
    in BaseNavigationContainer (at NavigationContainer.tsx:132)
    in ThemeProvider (at NavigationContainer.tsx:131)
    in NavigationContainerInner (at testProvider.tsx:32)
    in NavigationProvider (at App.tsx:17)
    in App (at hatman/index.tsx:22)
    in Root (at CodePush.js:585)
    in CodePushComponent (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)

package versions:

"react": "17.0.2",
"react-native": "0.67.2",

"@react-navigation/material-top-tabs": "^6.2.1",
"@react-navigation/native": "^6.0.10",
"@react-navigation/native-stack": "^6.6.1",
"react-native-gesture-handler": "^2.4.0",
"react-native-pager-view": "^6.0.0-rc.1",
"react-native-paper": "^4.12.0",
"react-native-tab-view": "^3.1.1",

targeted device:

Android

Variable in the useState not updating in useEffect callback

const Tweet = ({ tweet, checkedList, setCheckedList }) => {
  const [isChecked, setChecked] = useState(false);
  useEffect(() => {
    checkedList === [] && setChecked(false);
  }, [checkedList, isChecked]);
  return (
    <div className="tweet">
      <h3>Name : {tweet.name} </h3>
      <p>{tweet.tweet}</p>
      <input
        type="checkbox"
        checked={isChecked}
        onChange={() => {
          setChecked(!isChecked);
          checkedList.find((e) => e === tweet.id) === undefined
            ? setCheckedList([...checkedList, tweet.id])
            : setCheckedList(checkedList.filter((e) => e !== tweet.id));
        }}
      />
    </div>
  );
}; 

I have a tweet component that has its own state. There is an external checkedList with is basically an array of checked tweet ids.
But once I reset the checkedList = [] , I am trying to reset the checked tweets by useEffect. But can’t do it.
I want all tweets state to be unchecked. What am I doing wrong?

How can I disable a checkbox until data are load?

I need to disable checkboxes until the page load the data(products) and then enable them again,
this is my code for loading data:

function loadCounter(filterCounter) {
$.each(filterCounter.FilterCounter, function (key, value) {
    if (value.Count !== 0) {
        $("#filter .btn-groupl label :input[value='" + key + "']").parent("label").find("span.items-amount").text(value);
        $("filter .btn-group label :input[value='" + key + "']").parent("label").show();
    } else {
       ;
        $("filter .btn-group label :input[value='" + key + "']").parent("label").hide();
        
    }
});