I used this guide to set up authentication with my api using jwt
token authentication from Django
rest framework. I can log in just fine. But currently I set up another endpoint to get the user info of the currently authorized user (determined by the token they send with the request).
It's dispatched like so (done some time after the user logs in)
fetchUser: () => dispatch(loadUser()),
My action to load username:
import { RSAA } from 'redux-api-middleware';
import withAuth from '../reducers'
export const USER_REQUEST = '@@user/USER_REQUEST';
export const USER_SUCCESS = '@@user/USER_SUCCESS';
export const USER_FAILURE = '@@user/USER_FAILURE';
export const loadUser = () => ({
[RSAA]: {
endpoint: '/api/user/info/',
method: 'GET',
headers: withAuth({}),
types: [
USER_REQUEST, USER_SUCCESS, USER_FAILURE
]
}
});
Reducer:
import jwtDecode from 'jwt-decode'
import * as user from '../actions/user'
const initialState = {};
export default (state=initialState, action) => {
switch(action.type) {
case user.USER_SUCCESS:
return action.payload;
default:
return state
}
}
export const userInfo = (state) => state.user;
Reducer index.js
:
export function withAuth(headers={}) {
return (state) => ({
...headers,
'Authorization': `Bearer ${accessToken(state)}`
})
}
export const userInfo = state => fromUser.userInfo(state.user);
But when I try to get the user info of the logged in user, I get an error..
TypeError: Cannot read property 'type' of undefined
Why is the action type undefined?
Note: I tagged this with thunk because my project does use thunk, but not for this bit of redux.
Edit: My middleware.js
and my store.js
.
loadUsername
function? why do you have two of them? (one in the reducer) - aziumonSubmit
is calling the one in my actions file. The other one is a state access method used in mymatchStateToProps
. I just didn't bother giving them different names. I also commited all my current changes if you want to look at the full code. I'll add the relevant files as links in my post for easy access. - cclloyd