Fairly basic boolean value set up in my redux store to know whether a sidebar is expanded or not. The problem I'm facing is that (although the default value is false), whenever I click the toggle button, false is outputted first. But if it is initially false then when it is clicked first it should be true.
I was having this problem with local state, so I switched to redux as I know state is async. Was hoping managing the value via reducers in the redux store would fix it.
// Fetch redux state
const sidebar = useSelector(state => state.sidebar);
const { isExpanded } = sidebar;
const toggleSidebar = () => {
dispatch({
type: TOGGLE_SIDEBAR,
payload: !isExpanded
});
console.log(isExpanded);
}
The store and reducer is fairly self explanatory:
import { TOGGLE_SIDEBAR } from '../types/sidebar.types'
const initialState = {
isExpanded: false
}
export const sidebarReducer = (state = initialState, action) => {
switch(action.type) {
case TOGGLE_SIDEBAR:
return {
isExpanded: action.payload
}
default:
return state
}
}
Store.js
const reducer = combineReducers({
sidebar: sidebarReducer
});
const initialState = {
}
const middleware = [thunk];
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;