Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
Trying to declare variable within useEffect:

I'm really not sure what I am doing wrong

Please help out...

Is there a better way to access a variable declared within the useEffect?

Thanks

So I have the following code - but I get the error: [TypeError: "setDevice" is read-only]

const [device, setDevice] = useState( '' );
  React.useEffect(() => {
    const device_id = async () => {
      var DeviceInfo = require('react-native-device-info');
      var deviceId = DeviceInfo.getUniqueId();
      const filePath = RNFS.DocumentDirectoryPath + deviceId + "_secret.json";
      if (await RNFS.exists(filePath)){
        RNFS.readFile(filePath, 'utf8')
        .then((contents) => {
          try{
            // setDev = String(contents);
            var JSONObject = JSON.parse(contents);
            console.log(JSONObject['device_id']); 
            setDevice = JSONObject['device_id'];
          }catch(err){
            console.log("Error: ", err);
          }
          
        });
        console.log("FILE EXISTS: " + filePath);
    } else {
      function makeid() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      
        for (var i = 0; i < 5; i++)
          text += possible.charAt(Math.floor(Math.random() * possible.length));
      
        return text;
      }
      var dev_id = makeid() + deviceId;
      var id = '{"device_id" : "'+dev_id+'"}';
      RNFS.writeFile(filePath, id, 'utf8')
        .then((success) => {
          console.log('FILE WRITTEN!');
          navigation.dispatch(resetReachOutPreferences)
        })
        .catch((err) => {
          console.log(err.message);
        });
      } 
    }
    device_id();
  }, []);
  console.log("ID: " + device);

I've tried useState(null)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From the React documentation on the State hook:

What does useState return? It returns a pair of values: the current state and a function that updates it.

So in this case, setDevice is a function that can be used to update the value of device (which will be reflected on subsequent renders). Instead of assigning to it, you should call it with the new value as its argument, e.g.:

setDevice(contents);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda