sabinz
sabinz

Reputation: 1

react redux does not dispatch

I am developing an ecommerce app with react and I want to integrate redux for state management

I created the user reducer and called it in reducers/index.js

I then created a redux store in index.js

I tried changing the state using dispatch when useEffect is called but it is not working.

I want stanley Joy to show on the state when useEffect is called but user is always null.

UserReducer

export const userReducer = (state = null, action) =>{
    switch(action.type){
        case "LOGGED_IN_USER":
            return action.payload;
        case "LOGOUT":
            return action.payload;
        default:
            return state
    }
};

Reducers/index.js

import { combineReducers } from "redux";
import {userReducer} from './userReducer'

export const rootReducer = combineReducers({
    user: userReducer,
});

export default rootReducer;

app.js

import { useDispatch } from 'react-redux';

function App() {
  
  const dispatch = useDispatch();

  useEffect(() => {
    return () => {
      dispatch({
          type: "LOGGED_IN_USER",
          payload: {
            name: "stanley Joy",
          },
      })
  }
}, [])
}

index.js

import {composeWithDevTools} from 'redux-devtools-extension'
import { rootReducer } from './reducers';
const store = createStore(rootReducer, composeWithDevTools())    
ReactDOM.render(
  // <React.StrictMode>
  <Provider store={store}>
   <BrowserRouter>
    <App />
    </BrowserRouter>
    </Provider>,
  // </React.StrictMode>,
  document.getElementById('root')
);

Upvotes: 0

Views: 32

Answers (1)

Vijay Thomas
Vijay Thomas

Reputation: 41

2 solutions

  1. Change action.payload to action.payload.name in userReducer
  2. change dispatch object to below
      dispatch({
          type: "LOGGED_IN_USER",
          payload: "stanley Joy",
      })

Upvotes: 0

Related Questions