简体   繁体   中英

React-redux: User Information not getting stored in redux after login

hey guys I am new to react-redux, I am trying to store user information in redux store after the login, I am using a django backend for this.

consoling out the user in app.js gives me a null value and it shows a typerror TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) .

Can anyone tell me, what I did wrong and how to properly do it?

This is the code.

store.js

import {configureStore} from '@reduxjs/toolkit';
import userReducer from '../features/UserSlice';

export default configureStore({
    reducer: {
        user: userReducer,

    },
});

UserSlice.js

import {createSlice} from '@reduxjs/toolkit';

export const userSlice = createSlice({
    name: 'user',
    initialState: {
        user: null,
    },

    reducers: {
        login: (state, action) => {
            state.user = action.payload;
        },

        logout: (state) => {
            state.user = null;
        }
    },
})

export const {login, logout} = userSlice.actions;

export const selectUser = state => state.user.user;

export default userSlice.reducer;

login.js

const dispatch = useDispatch();


const userInfo = async function userProfileInfo() {
    await axiosInstance.get(url).then((res) => {
        const currentUser = res.data;
        dispatch(login({
            user: currentUser,
        }))
    })
}


const handleSubmit = (e) => {
        e.preventDefault();
        // console.log(formData);

        axiosInstance
            .post(`api/accounts/token/`, {
                email: formData.email,
                password: formData.password,
            })
            .then((res) => {
                localStorage.setItem('access_token', res.data.access);
                localStorage.setItem('refresh_token', res.data.refresh);

                userInfo();
                
                history.push('/');  
                // console.log(res);
                 // console.log(res.data);
            });
        
    };

index.js

<Provider store={store}>            
    <Route exact path="/login" component={HomeScreen} />
    <Route exact path="/" component={App} />
</Provider>

Thanks

Maybe this will help:

const userInfo = async function userProfileInfo() {
  //return a promise here
  return await axiosInstance.get(url).then((res) => {
    const currentUser = res.data;
    dispatch(
      login({
        user: currentUser,
      })
    );
  });
};

const handleSubmit = (e) => {
  e.preventDefault();
  // console.log(formData);

  axiosInstance
    .post(`api/accounts/token/`, {
      email: formData.email,
      password: formData.password,
    })
    .then((res) => {
      localStorage.setItem(
        'access_token',
        res.data.access
      );
      localStorage.setItem(
        'refresh_token',
        res.data.refresh
      );
      //wait for userInfo to finish
      return userInfo();
    })
    .then(() => {
      //here userInfo is finished (can have failed too)
      history.push('/');
      // console.log(res);
      // console.log(res.data);
    });
};

Normally one would do this with thunk actions:

const fetchThunk (arg)=>(dispatch,getState)=>{
  dispatch(loading(arg));
  fetch(arg).then(
    result=>dispatch(success(result)),
    error=>dispatch(failed(error))
  )
}

That means you have to store the status of the logged in user in the redux state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM