Reputation: 9678
I have a local .json
file that I wish to use as a starting point for my state. I then plan to store the state in AsyncStorage
. But my concern is that the import is async and I will get some conflicts.
This is what I'm currently doing
import { data } from './src/data.json'
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data,
}
this.updatePitch = this.updatePitch.bind(this)
}
...
}
But should I do this instead?
async componentDidMount() {
await this.setState({ data })
}
(I'm seeing some layout issues when doing it and a lot of warnings about other life-cycle methods will be deprecated)
and then perhaps do some Promise.all
when trying to hook it up with AsyncStorage
?
What the best way to use a local .json
file as a "boilerplate/template"
and then store the revised version locally?
Upvotes: 1
Views: 217
Reputation: 11260
Importing bundled json is synchronous (it's just like importing from a js file).
Your constructor is fine.
If you use Redux, you can import the json and use it as the initial state in your reducer. You can then persist the Redux state with redux-persist. Redux is highly recommended unless your app is really simple.
Otherwise, you can simply store the state to AsyncStorage
whenever it's updated, and read from AsyncStorage
in componentDidMount
and call setState
with the stored state for initialisation.
a lot of warnings about other life-cycle methods will be deprecated
This is a bug in RN 0.55.1, upgrade to >=0.55.2 to fix it.
Upvotes: 2