I am relatively new to react, react native and redux and I have one question about fetching the data from the api and updating the state.
What I want to do is: - each time a user opens the screen (i.e Posts) I want to fetch data from the api and update the state.
So that: - I always have newly fetched data in the state and rendered on the screen.
If I fetch the data only in componentDidMount lifecycle method then I won't always have fresh data.
Example: There are two screens Post and Posts. If a user opens posts screen for the first time then componentDidMount is triggered and posts are fetched and rendered. Then he goes to Post screen adds a new post and goes back to Posts screen then he will not see that new post because the posts will be displayed from the state fetched in componentDidMount method.
What is the best way to handle this and always have latest data?
class Posts extends Component {
componentDidMount() {
this.props.fetchPosts();
}
componentDidUpdate(prevProps) {
this.props.fetchPosts();
}
render () { ... }
}
const mapStateToProps = state => {
return {
posts: state.posts.posts,
loading: state.posts.loading,
}
}
const mapDispatchToProps = dispatch => {
return {
fetchPosts: () => dispatch(actions.fetchPosts()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Posts)
Action
export const fetchPosts = () => {
return dispatch => {
dispatch(fetchStarted());
apiFetchPosts()
.then(({data}) => {
const posts = data.data;
dispatch(fetched(posts))
})
.catch(error => {
dispatch(fetchFailed(error));
})
}
}
const fetchStarted = () => {
return {
type: actionTypes.POSTS_FETCH_START,
}
}
const fetched = (posts) => {
return {
type: actionTypes.POSTS_FETCH_SUCCESS,
posts,
}
}
const fetchFailed = (error) => {
return {
type: actionTypes.POSTS_FETCH_FAILED,
}
}