Persist a variable

1

I have a code in JS that has a varible with the idea of keeping a value in a constant way. The problem is that when calling that file again the variable is reset to undefined.

const rpcURL = "http://localhost:7545";
var address, key;

function init() {
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    web3 = new Web3(new Web3.providers.HttpProvider(rpcURL));
}
}

How can I solve this, persisting the value I establish once?

    
asked by Eduardo 17.12.2018 в 11:43
source

1 answer

2

If you need to persist during the current session you could use SessionStorage or during multiple sessions you could use LocalStorage

An example with SessionStorage

// salva web3 en sessionStorage, es importante notar la función JSON.stringify, 
// estoy asumiendo que la variable web3 es un objeto, 
// sessionStorage solo guarda strings como valores, 
// por lo que hay que transformar el objeto en un string primero
sessionStorage.setItem('web3', JSON.stringify(web3));

// Para recuperar la data se usa la función getItem, pero como guardamos un objeto en forma de string, tenemos que hacer el camino inverso
let web3 = JSON.parse(localStorage.getItem('web3'));

so your code would look something like this:

const rpcURL = "http://localhost:7545";
var address, key;

function init() {
  let web3 = JSON.parse(localStorage.getItem('web3'));
  if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
  } else {
    web3 = new Web3(new Web3.providers.HttpProvider(rpcURL));
  }
  sessionStorage.setItem('web3', JSON.stringify(web3));
}

LocalStorage functions are similar

    
answered by 17.12.2018 / 12:04
source