Search code examples
javascriptreact-nativereduxreact-reduxredux-thunk

How to start fetch with redux on App start?


after setup a simple counter for notifications. i'd like to fetch the notifications on the app start to show how many notifications received.

here is the configuration: reducer:

index.js

import { combineReducers } from "redux";
import posts from "./posts";
import filteredPosts from "./filteredPosts";
import notifications from "./notifications";

export default combineReducers({
  posts,
  filteredPosts,
  notifications
});

notification.js

import * as types from "../actions/types";
const initialState = [];

export default (state = initialState, action) => {
  switch (action.type) {
    case types.LOAD_NOTIFICATIONS:
      return action.notifications;
    default:
      return state;
  }
};

actions

type.js

export const FILTERED_POST = "FILTERED_POST";
export const LOAD_POSTS = "LOAD_POSTS";
export const LOAD_NOTIFICATIONS = "LOAD_NOTIFICATIONS";

notification.js

import * as types from "./types";
import { fetchNotifications } from "../service/";

export const getNotifications = auth_token => dispatch =>
  fetchNotifications(auth_token)
    .then(res => {
      return res.json();
    })
    .then(data => {
      dispatch({
        type: types.LOAD_NOTIFICATIONS,
        notifications: data.notifications
      });
    })
    .catch(err => {
      console.log(err);
    });

And service

index.js

import { apiEndpoint } from "./config";

export const fetchPosts = auth_token =>
  fetch(`${apiEndpoint}posts`, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Access: auth_token
    }
  });

export const fetchNotifications = auth_token =>
  fetch(`${apiEndpoint}notifications`, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Access: auth_token
    }
  });

the apiEndpoint is the api address So, after configure the notification badge component and add it to the router the app load the posts because is the home screen but not the notifications.

to check i placed the notification badge component as the home screen to first load and still not get the notifications. So, please someone can clarify how to fetch use redux on the app start or before or right after?

export const Logged = createBottomTabNavigator(
  {
    Notification: {
      screen: Notification,
      navigationOptions: {
        tabBarLabel: "Notification",
        tabBarIcon: () => {
          <NotificationIcon />;
        }
      }
    },

Solution

  • Well there are a number of things which could be wrong, firstly I would check the response from the endpoint, using a tool like postman, if the response is what you expect, then I would suggest creating a root component e.g AppComponent and within it, in your componentDidMount you can dispatch a getNotifications action using mapDispatchToProps