Issue
I'm trying to read a json file in my path and store its content in a useState variable I tried a lot and searched for solutions but did not find anything
mydata.json:
{
"key":"value"
}
my code :
import React, { useState } from 'react';
import { View,Button,Text, StyleSheet } from 'react-native';
import RNFS from "react-native-fs";
function App({route}){
const [jsonData, setJsonData] = useState({});
try {
RNFS.readFile("mydata.json","utf-8", function(err,data){
const jsonDataObject = JSON.parse(data.toString());
setJsonData(jsonDataObject);
});
} catch (error) {
console.error(error);
}
return (
<View style={styles.content}>
<Text>
hello
</Text>
<Button onPress={()=>(console.log("your json : ",jsonData))} title='print' />
</View>
);
}
styles = StyleSheet.create(
{
content:{
flex:1,
alignItems:"center",
justifyContent:"center"
}
}
)
export default App;
It is supposed to read the file, put it in the jsonData variable, and then print the content when the button is pressed
When I press the button it shows me :
LOG : {}
LOG : {}
LOG : {}
Expected result:
LOG : {"key":"value"}
LOG : {"key":"value"}
LOG : {"key":"value"}
Please help me and thank you
Solution
There are few things wrong with your code. If your readFile block of code actually managed to execute you would get stuck in an infinite set state loop. All non-hook code is called at every render. So as your code currently exist, you are setting state every time you read the file. Setting state causes a re-render; and you read the file every time there's a re-render.
You dont actually get to see this happen because your callback is never actually being executed. RNFS.readFile doesnt take a callback as an argument. It instead returns a promise. So your code should be something like this:
RNFS.readFile("mydata.json","utf-8")
.then(fileContents=>{
const jsonDataObject = JSON.parse(fileContents)
setJsonData(jsonDataObject)
})
.catch(error=> {
console.error(error);
})
And then to avoid the set state loop you should wrap this code in an useEffect
with an empty dependency array:
useEffect(()=>{
RNFS.readFile("mydata.json","utf-8")
.then(fileContents=>{
const jsonDataObject = JSON.parse(fileContents)
setJsonData(jsonDataObject)
})
.catch(error=> {
console.error(error);
})
},[])
Answered By - PhantomSpooks
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.