Home > Mobile >  Trying to declare variable within useEffect:
Trying to declare variable within useEffect:

Time:04-06

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)

CodePudding user response:

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);
  • Related