Have to run function 2 times for setting value to state in react?

Viewed 44

Code:-enter image description here

const [TimeStampsFromFile, setTimeStampsFromFile] = useState([])
const FilePicker = async () => {
        var RNFS = require('react-native-fs')
        // Pick a single file
        try {
            const res = await DocumentPicker.pick({
                type: [DocumentPicker.types.plainText],
            })
            const filepath =
                RNFS.ExternalStorageDirectoryPath + '/' + 'TimeStamps' + '/' + res.name
            const file = await RNFS.readFile(filepath)

            setTimeStampsFromFile(await file.split('\n'))
            console.log('file data' + TimeStampsFromFile)
        } catch (err) {
            if (DocumentPicker.isCancel(err)) {
                // User cancelled the picker, exit any dialogs or menus and move on
            } else {
                throw err
            }
        }
    }

this function runs on pressing a button in my react native app:-

On pressing the first time, it needs to return value but it simply returns nothing. But on pressing the second time it returns the value. (Why is that??) or Am I making some mistakes in code??

The same thing is also happing with my other button too.

I found this answer : - hooks not set state at first time but not able to get solution of my problem (if you can help from this answer)

1 Answers

TimeStampsFromFile is empty the first time you log it because setTimeStampsFromFile is async. If you want to log TimeStampsFromFile when value will be updated you could use useEffect hook like:

useEffect(() => {
   console.log(TimeStampsFromFile);
}, [TimeStampsFromFile]);

In this way, every time TimeStampsFromFile changes his value, useEffect will be called and log will show current value.

If you need to get the value of the TimeStampsFromFile from FilePicker function, is not necessary to get this value from TimeStampsFromFile. You could do something like:

...
const splitFile = await file.split('\n');
setTimeStampsFromFile(splitFile)
console.log('file data' + splitFile)
...
Related