Get users birthday from Facebook Graph API - react-native

Let me start by saying I see other answered questions with this a similar title but nothing is working for me.
I'm trying to get the users Birthday from Facebooks API, I'm using expo-auth-session.
I can successfully get the users ID, email and name but nothing else.
Here is my code, what am I missing?
const [request, response, promptAsync] = Facebook.useAuthRequest({
// clientId: '2877415105738397',
androidClientId: FacebookClientId,
iosClientId: FacebookClientId,
expoClientId: FacebookClientId,
scopes: ['user_birthday '],
redirectUri: makeRedirectUri({ useProxy: true })
});
Once I have the access_token
await axios.get(`https://graph.facebook.com/v15.0/me?fields=id,name,email,birthday&access_token=${token}`)
But I only get the {"email": "email#gmail.com", "id": "123415656565", "name": "Name"}
I do have app review permissions
UPDATE, FULL COMPONENT BELOW
import * as React from 'react';
import { View } from 'react-native';
import * as AppAuth from 'expo-auth-session';
import { useAuthRequest } from 'expo-auth-session/build/providers/Facebook';
import { FacebookClientId } from '../config/constant';
import { TouchableOpacity } from 'react-native';
import { FacebookIcon } from '../assets/SvgIcons/FacebookIcon';
import { Styling } from '../assets/style/styling';
import { useEffect, useState } from 'react';
import { onSignupExternal } from '../store/user/user.action';
import { useNavigation } from '#react-navigation/core';
import { useDispatch, useSelector } from 'react-redux';
const useProxy = Platform.select({ web: false, default: true, 'android': true, 'ios': true });
const discovery = {
authorizationEndpoint: 'https://www.facebook.com/v6.0/dialog/oauth',
tokenEndpoint: 'https://graph.facebook.com/v6.0/oauth/access_token',
};
export const FaceBook = ({ setLoading }) => {
const [userData, setUserData] = useState({})
const navigation = useNavigation()
const dispatch = useDispatch();
const { user } = useSelector((storeState) => storeState.userModule);
const clientId = FacebookClientId;
const scopes = ['public_profile', 'email', 'user_birthday'];
const [request, response, promptAsync] = useAuthRequest(
{
clientId,
scopes,
useProxy,
redirectUri: AppAuth.makeRedirectUri({
native: 'com.myapp.app:/',
useProxy,
}),
},
{useProxy: useProxy},
discovery
);
async function handlePress() {
try {
const result = await promptAsync();
if (result.type === 'success') {
setLoading(true)
getUserData(result.params.access_token)
} else {
// The user cancelled the login or an error occurred. You can inspect the result object for more details.
console.log('Login failed :(', result);
}
} catch (e) {
console.error(e);
}
}
async function getUserData(token) {
let response = await fetch(`https://graph.facebook.com/me?fields=id,name,email,birthday&access_token=${token}`);
const userInfo = await response.json()
console.log(userInfo)
setUserData({
user_email: userInfo.email,
user_id: userInfo.id,
user_full_name: userInfo.name,
user_ref_id: null,
auth_system: 'Facebook',
user_dob: null
})
}
useEffect(() => {
const getUser = async () => {
let updateUserData = userData
// let ref_id = await utilService.convertMailToAsciiCode(userData.user_id)
// updateUserData.user_ref_id = ref_id
return Object.keys(userData).length !== 0 && dispatch(onSignupExternal(userData))
};
getUser()
}, [userData])
useEffect(() => {
if (user !== null && user?.user_id !== undefined) {
setLoading(false)
return navigation.navigate("Dashboard")
}
}, [user])
return (
<TouchableOpacity style={Styling.facebookLoginBtn}
onPress={handlePress}>
<View style={Styling.googleIcon}><FacebookIcon /></View>
</TouchableOpacity>
)
}

Related

Multiple useEffect in react-native to achieve mentioned functionality

I need help with the async nature of Async storage and axios api. Here's the functionality that I am trying to achieve ->
send request to two separate api to get some data.
display that data on the screen with some additional text
api request are authenticated so a token is passed as Authentication Header
I have attached the current implementation, I am having the a number of errors in this
Errors:
Login_token not set in state after fetching from Async Storage.
Data not set in state after api call
both resulting in either failed api calls or undefined state errors on render
This is my code.
import React, { FunctionComponent, useEffect, useCallback, useState} from 'react';
import { StyleSheet, View} from 'react-native';
// chat
import { GiftedChat } from 'react-native-gifted-chat';
// navigation
import { RootStackParamList } from '../../navigators/RootStack';
import { StackScreenProps } from '#react-navigation/stack';
export type Props = StackScreenProps<RootStackParamList, "Chat">;
// api
import { Convo_details, Send_Msg, List_Msg, Expert_Public_Profile } from '../../api/UserApi';
import Spinner from 'react-native-loading-spinner-overlay';
import AsyncStorage from '#react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';
const Chat: FunctionComponent<Props> = ({ navigation, route, ...props }) => {
// console.log(props.route.params);
const [login_token, setlogin_token] = useState('')
const [conversation_id, setconversation_id] = useState('')
const [conversation_details, setconversation_details] = useState({})
const [currentuser, setcurrentuser] = useState({})
const [loading, setLoading] = useState(false);
const [expertuid, setexpertuid] = useState('')
const [ExpertProfile, setExpertProfile] = useState({})
const [messages, setMessages] = useState([]);
useEffect(() => {
getlogintoken()
console.log("####################################","getlogintoken");
}, [])
/* conversationid */
useEffect(() => {
if (route.params != null) {
setconversation_id(route.params[0])
}
console.log("####################################","conversation id");
}, [])
/* expert uid */
useEffect(() => {
if (route.params != null) {
setexpertuid(route.params[1])
}
console.log("####################################","expert uid");
}, [])
/* expert public profile */
useEffect(() => {
getexpertpublicprofile()
getConvo_details()
console.log("####################################","convo_details");
}, [])
useEffect(() => {
// get current user
AsyncStorage.getItem("currentuser").then(res => {
if (res != null) setcurrentuser(res)
else alert("Current user not found")
})
console.log("####################################","current user");
}, [])
// set welcome msg
useEffect(() => {
if (Object.keys(conversation_details).length != 0 && Object.keys(ExpertProfile).length != 0)
setwelcomemsg()
}, [])
const onSend = useCallback(async (messages = []) => {
// console.log(messages[0].text);
setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
const data = {
conversation_id: "f98d6851-a713-4f58-9118-77a779ff175f",//conversation_id,
message_type: "TEXT",
body: messages[0].text
}
const res: any = await Send_Msg(data, login_token)
.catch(error => {
alert(`Send_Msg -> ${error}`)
console.log(error);
return
})
if (res.status == 200) {
console.log(res.data);
} else console.log(res);
}, [])
const getexpertpublicprofile = async () => {
setLoading(true)
const res: any = await Expert_Public_Profile(expertuid, login_token)
.catch(error => {
setLoading(false)
console.log("Expert public profile ->");
alert(`Expert public profile ->${error.message}`)
console.log(error);
return
})
setLoading(false)
if (res.status === 200) setExpertProfile(res.data)
else {
alert(`get expert public profile${res.data.message}`)
console.log("getexpertpublicprofile -->");
console.log(res.data);
}
}
const getlogintoken = () => {
AsyncStorage.getItem("login_token").then(res => {
if (res != null) {
setLoading(false)
setlogin_token(res)
}
else alert("No login token found")
})
}
const getConvo_details = async () => {
setLoading(true)
const res: any = await Convo_details(conversation_id, login_token)
.catch(error => {
setLoading(false)
alert(`Convo_details-->${error.message}`)
console.log("Convo_details -->");
console.log(error);
return
})
setLoading(false)
if (res.status === 200) setconversation_details(res.data)
else {
alert(`get convo details-> ${res.data.message}`)
console.log("getConvo_details -->");
console.log(res.data);
}
}
const setwelcomemsg = () => {
try {
let user = JSON.parse(currentuser)
let messages = [
{
_id: uuid.v4().toString(),
conversation_id: conversation_details.conversation_id,
created_at: new Date(),
from: conversation_details.recipient.user_uid,
type: "TEXT",
text: `About Me - ${ExpertProfile.bio}`,
user: {
_id: conversation_details.recipient.user_uid,
}
},
{
_id: uuid.v4().toString(),
conversation_id: conversation_details.conversation_id,
created_at: new Date(),
from: conversation_details.recipient.user_uid,
type: "TEXT",
text: `My name is ${conversation_details.recipient.name}`,
user: {
_id: conversation_details.recipient.user_uid,
}
},
{
_id: uuid.v4().toString(),
conversation_id: conversation_details.conversation_id,
created_at: new Date(),
from: conversation_details.recipient.user_uid,
type: "TEXT",
text: `Hi ${user.full_name}`,
user: {
_id: conversation_details.recipient.user_uid,
}
}]
setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
} catch (error) {
console.log("try -> set welcome msg");
console.log(error);
return
}
}
return (
<View style={styles.maincontainer}>
<Spinner
visible={loading}
textContent={'Loading...'}
textStyle={{ color: '#FFF' }}
/>
<GiftedChat
messages={messages}
onSend={messages => onSend(messages)}
user={{
_id: currentuser.user_uid,
}}
isTyping={false}
scrollToBottom={true}
showAvatarForEveryMessage={true}
renderAvatar={() => null}
/>
</View>
);
}
export default Chat;
const styles = StyleSheet.create({
maincontainer: {
flex: 1,
},
});
When axios returns, it usually give the response as res.data, so in your case, try either res.data or res.data.yourToken (I'm not sure how it's your object).
Gurav,
As far as your code above, The api call's will trigger even before you get currentuser or loginToken. You have to handle the api call after getting the currentuser and loginToken. This can be gracefully handled with async, await.
example code:
useEffect(() => {
getData()
}, [])
useEffect(() => {
if(login_token && currentuser) {
//The api call goes here after you get the logintoken andcurrentuser.
// The above condition is just an example but will vary based on your requirements
}
}, [login_token, currentuser])
const getData = async () => {
await getlogintoken()
await getcurrentuser()
}
const getlogintoken = async () => {
await AsyncStorage.getItem("login_token").then(res => {
if (res != null) {
setLoading(false)
setlogin_token(res)
}
else alert("No login token found")
})
}
const getcurrentuser = async () => {
await AsyncStorage.getItem("currentuser").then(res => {
if (res != null) setcurrentuser(res)
else alert("Current user not found")
})
}

Application error: a client-side exception has occurred (see the browser console for more information) .NEXT JS

In my extjs application , authorization works on the local host , but the page server gives an error : Application error: a client-side exception has occurred (see the browser console for more information) . They want a login, password are saved to the database, when logging in, a redirect to a page protected via axios is successfully performed, and there is an error there.
The cook's locale is saved correctly, but apparently cannot be counted from there.
I added a header (Access-Control-Allow-Origin) to the request, it didn't help.
My service :
import axios, {AxiosError} from "axios";
import { Router, useRouter } from "next/router";
import { useQuery } from "react-query";
const host = process.env.HOST || 'http://localhost:3000'
// axios instance
export const apiClient = axios.create({
baseURL: host + "/api",
withCredentials: true,
headers: {
"Content-type": "application/json"
},
});
export type Admin = {
id: string
login: string
}
export type RedirectError = {
redirectUrl: string
}
export const getSession = async () => {
const response = await apiClient.get<Admin>('getSession')
return response.data
}
export const useSession = () => {
const router = useRouter()
const { isLoading, error, data, isSuccess } = useQuery<Admin, AxiosError<RedirectError>>('sid', getSession)
if (error) router.push(error.response.data.redirectUrl)
return { isLoading, error, data, isSuccess }
}
My api/getSession:
import type { NextApiRequest, NextApiResponse } from 'next'
import checkSession from '../../src/services/checkCookie'
export default async function getSession(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
try {
const sid = req.cookies['sid']
const admin = await checkSession(sid)
if (admin) {
const { id, login } = admin.admin
return res.send({ id, login })
}
const host = process.env.NODE_ENV === 'production' ? process.env.HOST : 'http://localhost:3000'
return res.status(401).send({ redirectUrl: host + '/admin/login' })
} catch (error) {
console.error(error)
res.status(500).send({ message: "" })
}
} else {
res.status(404).send({ message: "" })
}
}
checkSession in getSession api :
export default async function checkSession (token: string) {
// const token = req.cookies['sid']
if (typeof window === 'undefined' && token) {
const unsign = (await import('./signature')).unsign
const sessionToken = unsign(token, process.env.SECRET!)
if (sessionToken && typeof sessionToken === 'string') {
const db = (await import('../../prisma')).default
const session = await db.session.findUnique({ where: { sessionToken },
include: { admin: true } })
if (session) {
return { admin: session.admin }
}
}
}
}
Page with axios
import { NextPage } from "next"
import TableService from "../src/component/TableService"
import AdminLayout from "../src/component/admin/AdminLayout"
import { Admin, getSession, RedirectError, useSession } from "../src/services/apiClient"
import { useRouter } from "next/router"
import { CircularProgress } from "#mui/material"
const AdminTable: NextPage = () => {
const router = useRouter()
const {isLoading, error, data, isSuccess } = useSession()
if (isLoading) return <CircularProgress />
return (
<>
{data && <div>{data.login}</div>}
{isSuccess &&
<AdminLayout title="">
<TableService />
</AdminLayout>
}
{isLoading && <p>Loading..</p>}
{error && <p>Error occurred!</p>}
</>
)
}
export default AdminTable

Show user info on login - react native

I have my login working, it logs me in without problems and it enters the screen that I want, but when I want to show the information on the screen of the user that logs in, I have not been able to show the user information on the screen that it should load from database. I have tried to create an interface where I add the names of the fields as they are in the database but when calling them from my screen nothing is loaded
what I need is that when I log in to my screen protectedScreen.ts it shows me the data of the user that logs in
mi db: Tabla : usuarios campos: id, name, email, password, tipo_usuario
AuthContext.ts //where valid and login
import React,{ createContext, useEffect, useReducer } from "react";
import AsyncStorage from '#react-native-async-storage/async-storage';
import { SafeAreaView, StyleSheet, TextInput, View, Alert, TouchableOpacity, Text } from "react-native";
import cafeApi from "../api/cafeApi";
import { LoginData, LoginResponse, RegisterData, Usuarios } from "../interfaces/appinterfaces";
import { authReducer, AuthState } from "./AuthReducer";
type AuthContextProps = {
errorMessage: string;
token: string | null;
user: Usuarios | null;
status: 'checking' | 'authenticated' | 'not-authenticated';
signUp: (RegisterData: RegisterData) => void;
signIn: (loginData : LoginData) => void;
logOut: () => void;
removeError: () => void;
}
const authInicialState: AuthState = {
status:'checking',
token: null,
user: null,
errorMessage:''
}
export const AuthContext = createContext({} as AuthContextProps);
export const AuthProvider = ({children}: any) =>{
const[state, dispatch] = useReducer(authReducer,authInicialState);
useEffect(() =>{
checkToken();
}, [])
const checkToken = async () =>{
const token = await AsyncStorage.getItem('token');
//No token, no autenticado
if (!token) return dispatch({ type:'notAuthenticated'});
//hay token
const resp = await cafeApi.get('/usuarios/middlewares/Auth.php');
if(resp.status !== 200){
return dispatch({type:'notAuthenticated'});
}
await AsyncStorage.setItem('token', resp.data.token)
dispatch({
type: 'signUp',
payload:{
token: resp.data.token,
user: resp.data.usuarios
}
})
}
const signIn = async({correo, password}: LoginData) => {
try {
await fetch('https://www.miweb.com/apiPlooy/usuarios/login.php',
{
method:'POST',
headers:{
'Accept': 'application/json',
'content-Type': 'application/json'
},
body: JSON.stringify({"email":correo, "password" : password})
}).then(res => res.json())
.then(resData => {
if(resData.message == "Ha iniciado sesiĆ³n correctamente.") {
dispatch({
type: 'signUp',
payload: {
token: resData.token,
user: resData.usuarios
}
});
}else{
Alert.alert(resData.message)
}
});
}catch (error) {
dispatch({type: 'addError',
payload: error.response.data.msg || 'InformaciĆ³n incorrecta'})
}
};
return(
<AuthContext.Provider value={{
...state,
signUp,
signIn,
logOut,
removeError,
}}>
{children}
</AuthContext.Provider>
)
}
appinterfaces.ts // where I add the user db fields to be able to show them on the screen when I login
export interface LoginData{
correo: string;
password: string;
}
export interface LoginResponse{
usuarios: Usuarios;
token: string;
}
export interface Usuarios{
tipo_usuario: String;
email: String;
password: String;
name: String
}
ProtectedScreen.ts // This is my screen when I log in and where I want to show some field of my user that I log in but it is not shown.
interface Props extends StackScreenProps<any, any>{}
export const ProtectedScreen = ({navigation}: Props) => {
const {user, token} = useContext(AuthContext);
const {email, password, name, onChange} = useForm({
email:'',
password:'',
name:'',
});
return (
<>
<View style={loginStyles.formContainer}>
<Text>BIENVENIDO
Tipo usuario: {JSON.stringify(user.tipo_usuario, null, 50)}
</Text>
</View>
</>
)
}
code and api: https://github.com/Giovannychvz/react-native
//I add what I have found in case it is of any use I have a project in reactjs and it uses the same api as the react native project and when I log in it loads the data of the user who logged in, I don't know if it is of any use but I send the context of react:
Note: the only strange thing I found in this context of react is that user-info.php is being called and I am not calling this file from react native because the problem must be there but I have not been able to solve it.
context.js
import React, { createContext,Component } from "react";
import axios from 'axios'
import history from '../components/history';
export const MyContext = createContext();
// Define the base URL
const Axios = axios.create({
baseURL: 'https://www.miweb.com/apiPlooy/usuarios/',
});
class MyContextProvider extends Component{
constructor(){
super();
this.isLoggedIn();
history.push('/');
}
// Root State
state = {
showLogin:true,
isAuth:false,
theUser:null,
}
// Toggle between Login & Signup page
toggleNav = () => {
const showLogin = !this.state.showLogin;
this.setState({
...this.state,
showLogin
})
}
// On Click the Log out button
logoutUser = () => {
localStorage.removeItem('loginToken');
localStorage.clear();
history.push('/');
this.setState({
...this.state,
isAuth:false
})
}
registerUser = async (user) => {
// Sending the user registration request
const register = await Axios.post('register.php',{
name:user.name,
email:user.email,
password:user.password
});
return register.data;
}
loginUser = async (user) => {
// Sending the user Login request
const login = await Axios.post('login.php',{
email:user.email,
password:user.password
});
return login.data;
}
// Checking user logged in or not
isLoggedIn = async () => {
const loginToken = localStorage.getItem('loginToken');
// If inside the local-storage has the JWT token
if(loginToken){
//Adding JWT token to axios default header
Axios.defaults.headers.common['Authorization'] = 'bearer '+loginToken;
// Fetching the user information
const {data} = await Axios.get('user-info.php');
// If user information is successfully received
if(data.success && data.user){
this.setState({
...this.state,
isAuth:true,
theUser:data.user
});
}
}
}
render(){
const contextValue = {
rootState:this.state,
toggleNav:this.toggleNav,
isLoggedIn:this.isLoggedIn,
registerUser:this.registerUser,
loginUser:this.loginUser,
logoutUser:this.logoutUser
}
return(
<MyContext.Provider value={contextValue}>
{this.props.children}
</MyContext.Provider>
)
}
}
export default MyContextProvider;

Redux, Axios, and Redux Thunk with Expo 37

so i am using Redux redux-thunk redux-persist and axios all together here is my setup:
**action.js**
import axios from 'axios';
import * as type from './constants';
export const handleSignup = userDetails => async (dispatch) => {
const {
email, password, username, version,
} = userDetails;
return axios
.post('/users/signup', {
email,
password,
username,
platform: version,
})
.then((res) => {
dispatch({
type: type.USER_SIGNUP_SUCCESS,
payload: res.data,
});
axios.defaults.headers.common.Authorization = `Bearer ${
res.data.access_token
}`;
return res;
});
};
**api.js**
import axios from 'axios';
import configureStore from '../store/configureStore';
const { store } = configureStore();
axios.defaults.baseURL = 'http://baseurl/api/v1';
axios.defaults.headers.common['Content-Type'] = 'application/json';
const accesToken = store.getState().authentication.token;
if (accesToken) {
axios.defaults.headers.common.Authorization = `Bearer ${accesToken}`;
}
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.interceptors.response.use(
async response => response,
error => Promise.reject(error),
);
**configureStore.js**
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import { persistStore, persistCombineReducers } from 'redux-persist';
import rootReducer from '../reducers';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'root',
storage,
blacklist: ['name1', 'name2', 'name3'],
};
const middlewares = [thunk];
const enhancer = composeWithDevTools(applyMiddleware(...middlewares));
const persistedReducer = persistCombineReducers(persistConfig, rootReducer);
export default () => {
const store = createStore(persistedReducer, undefined, enhancer);
const persistor = persistStore(store, null, () => {
store.getState();
});
return { store, persistor };
};
and i got this code inside my reducer for the signup success action
case type.USER_SIGNUP_SUCCESS:
return {
...state,
...action.payload.data.user,
email: action.payload.data.user.email,
username: action.payload.data.user.username,
token: action.payload.data.access_token,
user_id: action.payload.data.user.id,
};
and finally, i am calling handleSignUp on a submit button click:
onSignupClicked = () => {
this.setState({
error: false,
errorMessage: [],
loading: true,
});
const { platform } = Constants;
const version = Object.keys(platform)[0];
const {
user: { email, password, username },
} = this.state;
const { handleSignup, navigation } = this.props;
handleSignup({
email,
password,
username,
version,
})
.then(() => {
this.setState({ loading: true });
navigation.navigate(NAV_INTRO);
})
.catch((err) => {
console.log('ERROR : ',err)
});
};
sorry for a long code, so now my problem is that as soon as the user presses signup i am automatically getting ERROR : Network Error message. it doesn't wait for the request to get completed i guess, but the confusing part for me is this same code works on a previous version of the app with Expo 30.0.0, now its running on Expo 37.0.0. and i have double checked the API no problem with that, my question is is there something wrong with his code? is there a reason for it to return Network Error so fast?
i know this is bulky but any suggestion would be nice, Thanks.
in case its important here are my versions:
"react-redux": "5.0.7",
"redux": "4.0.0",
"redux-devtools-extension": "^2.13.8",
"redux-logger": "3.0.6",
"redux-mock-store": "1.5.3",
"redux-persist": "5.10.0",
"redux-thunk": "2.2.0",

Asyncstorage in Redux action

I'm trying to use my access token (stored in Asyncstorage) in a Redux action. This is my code:
export function fetchData() {
const endpoint = 'someEndpoint.com';
let accessToken = '';
myAccessToken().then((token) => {
accessToken = token;
});
return (dispatch) => {
dispatch(getData());
axios.get(endpoint, { headers: { 'access-token': accessToken } })
.then(response => {
dispatch(getDataSuccess(response.data));
})
.catch(error => {
dispatch(getDataFailure(error));
});
};
}
const myAccessToken = async () => {
try {
const retrievedItem = await AsyncStorage.getItem('accessToken');
return retrievedItem;
} catch (error) {
return null;
}
};
But fetching of the key is obviously async, I'm not sure on how to use the accessToken in the API call. I'm not allowed to do something like this:
export function fetchData() {
const endpoint = 'someEndpoint.com';
myAccessToken().then((token) => {
return (dispatch) => {
dispatch(getData());
axios.get(endpoint, { headers: { 'access-token': token } })
.then(response => {
dispatch(getDataSuccess(response.data));
})
.catch(error => {
dispatch(getDataFailure(error));
});
};
});
}
My Store:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import app from './reducers';
export default function configureStore() {
return createStore(app, applyMiddleware(thunk));
}
Update
In the end I did it a little bit different, In my componentDidMount:
componentDidMount() {
AsyncStorage.getItem('accessToken').then((accessToken) => {
this.setState({ accessToken });
this.props.fetchData(accessToken);
});
}
Thanks, Kevin.
I think you should use redux-thunk library for asynchronous updates of the redux state. It's easy to configure in the store.js file:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux#>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Then, I would implement it like this:
export function fetchData() {
return async function(dispatch) {
const endpoint = 'someEndpoint.com';
const accessToken = await myAccessToken();
try {
const response = await axios.get(endpoint, { headers: { 'access-token': accessToken } });
return dispatch(getDataSuccess(response.data));
} catch (error) {
return dispatch(getDataFailure(error));
}
}
}