Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!