I need to get several variables declared in a function A to use it in a function B.
How can I do that with ReactJS ?
EDIT
Function A :
const FunctionA = (e) => {
setPopupOpen(true)
e.preventDefault()
// data du cartouche en cours
let dataDest = e.currentTarget.getAttribute('data')
let jdataDest = JSON.parse(dataDest)
let channelDest = jdataDest.channel
let numcartDest = jdataDest.data.NUM_CART
// data de l'item en cours de drag
let tot = e.dataTransfer.getData("mydatabrowser")
if (tot) { // d&d externe depuis browser
let dataItem = JSON.parse(tot)
console.log(dataItem)
console.log("drop from browser", dataItem)
//execution d&d externe
InsertItem(callbackDrag, props.ddo, dataItem.val.guid, channelDest, numcartDest, dataItem)
}
else { // d&d interne entre cartouches
FunctionB(dataOrig, dataDest)
}
}
e.dataTransfer.clearData()
if (!tot) {
//*
}
}
Function B :
const FunctionB = (dataOrig, dataDest) => {
if (dataOrig, dataDest) {
if (dndReplace) {
ReplaceItem(callbackDrag, props.ddo, dataItem.data.GUID_ITEM, channelDest, numcartDest, dataItem)
} else {
InsertItem(callbackDrag, props.ddo, dataItem.val.guid, channelDest, numcartDest, dataItem)
}
}
}
Functions A and B are in the same component.
I call the function A in a PopUp component.
Variables I need to get are dataDest and dataOrigin.
Assign all variables to Array or Object and pass it as parameter to the function B, if the function B is a functional component then you can pass it as props.
Please share your code so we can solve it and explain the solution with your code as an example :)
Related
According to this codesandbox I'm using to to generate a map on react and I have implemented the drawer plugin. here I want to delete the last shape I have added to the map and create and show the new map instead of the last shape. Is there nay performant way of doing that?
Store the last layer in a variable in the create event:
var lastLayer = null;
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType,
layer = e.layer;
if (type === "marker") {
const { lat, lng } = layer._latlng;
console.log(lat, lng);
}
if (type === "rectangle") {
const latlngs = layer._latlngs;
let thisPpp = "";
latlngs[0].map((item) => {
return (thisPpp += `LatLng(${item.lat}, ${item.lng}),`);
});
}
lastLayer = layer; // <---------------
drawnItems.addLayer(layer);
});
And then you can remove the last layer with:
if(lastLayer){
lastLayer.remove();
}
My controller return an array of variables.
return response()->json([$newBauxEnCours, $bienPrixEnBaisse]);
My method for call API Laravel
getProducts(status: string, typeTransac: string): Observable <any> {
let params = new HttpParams();
params = params.append('status', status);
params = params.append('typeTransac', typeTransac);
console.log(params);
if (status !== null && typeTransac !== null) {
// Conversion en nombre
return this.apiClient.get(this.ApiUrl, { params: params});
}else{
console.log('aucune valeur en params')
}
}
ngOnInit(){
this.ArchiveVente$ = this.dataMlsService.getProducts('Vendu', 'Vente');
console.log(this.ArchiveVente$);
}
My problem is : Why retrieve my variable $newBauxEnCours in Angular ?
Thanks
try like this
ngOnInit(){
this.dataMlsService.getProducts('Vendu', 'Vente').subscribe((response: any)=> {
console.log(response);
});
}
GetProducts returns this.apiClient.get() which returns a Observable. The Observable will not get executed until you subscribe to it.
Because the get call is asynchronous you must provide a function (callback) to the subscribe function that will get called when the get is finished.
this.ArchiveVente$ = this.dataMlsService.getProducts('Vendu', 'Vente').subscribe((response: any)=> {
console.log(response);
});
this.ArchiveVente$ is set to the observable. in your html you need to use it with the async pipe. e.g.
<li *ngFor="let varName of ArchiveVente$ | async">
{{ varName.name }}
</li>
you can also just add the data to the variable than you can use is without the async pipe
this.dataMlsService.getProducts('Vendu', 'Vente').subscribe((response: any)=> {
this.ArchiveVente = response;
});
see: https://angular.io/guide/observables for more info
I'm working in a project using React hooks. However I try to use a variable without useState hook to handle a variable. The thing is that when I'm running a function that contains an array operation, it seems like that is not took into account and skip that step.
I did the change that way (you'll see that soon in the code) because I'm using an array that is continuos adding more values, so I think that is easier to do in that way.
Can you please help me to fix that issue or explain me why is that doesn't working?
Here is the code:
let platosRegVent:any = []; // This is how I'm declaring my array
const agregarPlato = async () => {
if(validarCamposPlato()){
try{
let valorParcial = 0;
let platoExist = await encontrarPlato(config, rvPlato);
if(platoExist === true){
setAgregadoMin(true);
platoCodigo = await obtenerCodigoPlato(config, rvPlato);
platosRegVent.push({codigoPlato: platoCodigo, cantidad: rvCantidad}); // Here is where I'm adding more objects to my array.
let costoPlato = await obtenerValorPlato(config, rvPlato);
valorParcial = valorTotal;
setValorTotal(valorParcial += (costoPlato * parseInt(rvCantidad)));
setRvPlato('');
setRvCantidad('');
}
else{
toast.error('El plato ingresado no se ha encontrado.');
setRvPlato('');
}
}
catch(error){
toast.error('Un error inesperado ha ocurrido, por favor intente mas tarde.');
props.handleSubmit();
}
}
}
const finalizarRegVent = async () => {
console.log(agregadoMin);
if(validarCampos()){
try{
if(rvPlato !== '' || rvCantidad !== ''){
await agregarPlato();
}
if(agregadoMin === true){
rvCodigo = await crearRegistroVenta(config, valorTotal, fechaActual, regVentMesa);
platosRegVent.forEach( (plato : any) => { //Here is the operation of the array. It seems that this step is skipped.
crearRegVentPlato(config, rvCodigo, plato.codigoPlato, plato.cantidad);
});
setValorFinal(false);
}
else{
toast.error('Debe ingresar por lo menos un plato para completar el registro.');
}
}
catch(error){
toast.error('Un error inesperado ha ocurrido, por favor intente mas tarde.');
props.handleSubmit();
}
}
}
You should use useState() & useCallback() hook instead.
Because the mechanism of React only updated when detecting the change of state. If you create static variable, react can't update its value.
Alternatively, useRef() is solution for you.
I'm trying to write a function into a React component, but I am stuck with this error:
Uncaught Error: Module build failed: SyntaxError: "productMap" is read-only
Why is this happening? And how can I fix this, so I can use productMap?
Here is my function:
printReceipt() {
var products = this.props.updateBasket.products;
//create a map of products
const productMap = {};
for(let product of products) {
if(!productMap[product.id]) {
productMap[product.id] = 1;
} else {
productMap = productMap + 1;
}
}
console.log(productMap);
}
This is happening because poductMap is of type const and const cannot change through reassignment
Change it to a let or var instead
printReceipt() {
var products = this.props.updateBasket.products;
//create a map of products
let productMap = {};
for(let product of products) {
if(!productMap[product.id]) {
productMap[product.id] = 1;
} else {
productMap = productMap + 1;
}
}
console.log(productMap);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
Use let productMap={}; instead of const.
The const declaration creates a read-only reference to a value.
Reference
use ()=> FunctionName() instead of FunctionName()
When we call the function FunctionName(), it is just executed, but when we write () => FunctionName(), then it is only called when that particular operation is performed for example onPress.
FunctionName() sometimes doesn't work, and is only read-only, using () => FUnctionName, is a good way.
I am trying to fetch ordered data from Firebase and set it to state highscoreArray but it gives error "undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores })')
componentDidMount() {
const reference = database.ref("highscores");
// Pushing sorted data to highscoreArray.
reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
sortedHighscores = [];
snapshot.forEach(function (child) {
sortedHighscores.push({
"username": child.val().username,
"score": child.val().highscore
});
});
sortedHighscores = sortedHighscores.reverse();
console.log("sortedh", sortedHighscores); // fetch success
this.setState({highscoreArray: sortedHighscores}); // gives error
});
}
One of the major advantages of arrow functions is that it does not have it's own this value. It's this is lexically bound to the enclosing scope.
class Logger {
dumpData(data) {
var _this = this;
// this dumps data to a file and get the name of the file via a callback
dump(data, function (outputFile) {
_this.latestLog = outputFile;
});
}
}
// using arrow functions
class Logger {
dumpData(data) {
dump(data, outputFile => this.latestLog = outputFile);
}
}
1.this not accessible within loop so use variable let that = this the use that wherever you need this in this function.
componentDidMount() {
const reference = database.ref("highscores");
let that = this // here your variable declaration
// Pushing sorted data to highscoreArray.
reference.orderByChild("highscore").limitToLast(3).on("value", function (snapshot) {
sortedHighscores = [];
snapshot.forEach(function (child) {
sortedHighscores.push({
"username": child.val().username,
"score": child.val().highscore
});
});
sortedHighscores = sortedHighscores.reverse();
console.log("sortedh", sortedHighscores); // fetch success
that.setState({highscoreArray: sortedHighscores}); // gives error
});
}
Hope this will help you :) happy coding!
Inside the function callback the this has a different context. Either use an arrow function, or store a reference outside:
Arrow:
reference.orderByChild("highscore").limitToLast(3).on("value", (snapshot) => { ... });