Reputation: 1333
I am new to React Native and so would like to know the best practices regarding the following scenario.
My Notification screen component contains nested child components as follows:
NotificationsScreen ReadSection ReadList UnreadSection UnreadList
Where should I handle state and make my API calls?
Option 1:
In ScreenComponent constructor and componentDidMount:
this.state = {
loading: true,
notifications: [],
error: ''
componentDidMount() {
const headers = {
Authorization: this.props.jwt
};
axios({
method: 'GET',
url: 'http://localhost:3000/notifications',
headers: headers,
}).then((response) => {
this.setState({
notifications: response.data.data,
loading: false
then I would have to pass the notifications state object to the child components ReadList and UnreadList as props, filter out the read and unread notifications respectively and render the list.
Option 2:
Make the API calls to the API in the child List components:
constructor(props) {
super(props);
this.state = {
loading: true,
read_notifications: [],
error: ''
};
}
componentDidMount() {
const headers = {
Authorization: this.props.jwt
};
axios({
method: 'GET',
url: 'http://localhost:3000/notifications?status=read',
headers: headers,
}).then((response) => {
this.setState({
notifications: response.data.data,
loading: false
In this case I would have 2 API calls, one for each component which is not ideal, and I have no idea how to handle the loading render for the parent controller while the data loads, since the child only renders the list, not the entire screen.
So I guess Option 1 would be preferable but it means passing the entire array of notifications to the child components and doing the filtering on potentially hundreds of records in each child component.
Is there a third option I have not though of? Thanks in advance. BTW I am not using Redux (yet) so would like to avoid any solutions involving external flux libraries for now.
Upvotes: 0
Views: 288
Reputation: 520
There are two types of component as best practices. Stateful and Pure components. Some people also call them Container and Presentational components. State always should be handled by Stateful/Container components. Presentational components doens't handle state, only access parent components state.
Upvotes: 1