0
votes

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

extended error information

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.

1
where is your middleware code - Gaurav Paliwal
@GauravPaliwal Added them at the end of my post. - cclloyd
are you using the wrong loadUsername function? why do you have two of them? (one in the reducer) - azium
@azium I am certain I am using the right one. the dispatch from onSubmit is calling the one in my actions file. The other one is a state access method used in my matchStateToProps. 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

1 Answers

0
votes

The issue is that in store.js that thunk is applied before the redux-api-middleware middleware.

Just move it to after like this:

const store = createStore(
        reducer, {},
        compose(
            applyMiddleware(apiMiddleware, thunk, routerMiddleware(history)),
            window.devToolsExtension ? window.devToolsExtension() : f => f,
        ),
    );