I have this store: import { configureStore } from '@reduxjs/toolkit'; import userReducer…
- User
I have this store:
import { configureStore } from '@reduxjs/toolkit'; import userReducer from './slices/userSlice';
export const store = configureStore({ reducer: { user: userReducer } });
export type RootState = ReturnType; export type AppDispatch = typeof store.dispatch;
this slice:
import { User } from '@prisma/client'; import { createSlice } from '@reduxjs/toolkit';
interface UserState { value: User | null; }
// Define the initial state using that type const initialState: UserState = { value: null };
export const userSlice = createSlice({ name: 'user', initialState, reducers: { setUser: (state, action) => { const user = { ...action.payload, defaultOffice: null }; return user; } } });
export const { setUser } = userSlice.actions;
export const selectUser = (state: { user: UserState }) => state.user.value;
export default userSlice.reducer;
This function where I set the user:
export const appHomeOpenedCallback: Middleware< SlackEventMiddlewareArgs<'app_home_opened'>
= async ({ client, event, logger }) => { if (event.tab !== 'home') { // Ignore the
app_home_openedevent for everything // except for home screen as we don't support a conversational UI return; } try { const slackId = event.user; const user = await getUserBySlackId(slackId);const userModified = { ...user, settings: { ...user?.settings, defaultOffice: null } }; const offices = await getOffices(); const defaultOffice = user?.settings?.officeId; const defaultOfficeName = user?.settings?.defaultOffice.name; const isAdmin = user?.isAdmin || false; const generateView = async () => { if (user && defaultOffice) { const bookings = await getBookingsByOfficeId( defaultOffice, today, twoFridaysFromToday ); store.dispatch(setUser(userModified)); const { officeChatMembers, officeChatExists } = await getOfficeChatAndMembers(client, defaultOffice); return home( bookings, today, twoFridaysFromToday, slackId, officeChatExists, officeChatMembers || [], isAdmin, defaultOfficeName, offices ); } else { return createUser(); } }; await client.views.publish({ user_id: slackId, view: await generateView() });} catch (error) { logger.error(error); } };
But when trying to access the user here it returns null:
export const joinDayCallback: Middleware< SlackActionMiddlewareArgs
= async ({ body, ack, client }) => { try { await ack(); const date = format(parseISO(body.actions[0].value), 'EEEE - dd MMM');
const userStored = selectUser(store.getState()); console.log(userStored); const user = await getUserBySlackId(body.user.id); const defaultOffice = user?.settings?.officeId; const { startDate, endDate, defaultOption } = JSON.parse( body.view?.private_metadata || '' ); if (!defaultOffice) throw new Error('No default office set'); const office = await getOffice(defaultOffice); const officeAreasWithBookings = await getOfficeAreasWithBookings( defaultOffice, parseISO(body.actions[0].value) ); const officeAreaOptions = getOfficeAreaOptions(officeAreasWithBookings); if (office && officeAreaOptions) { await client.views.open({ trigger_id: body.trigger_id, view: joinDayModal( date, body.user.id, officeAreaOptions, startDate, endDate, defaultOption ) }); } else { throw new Error('No office found'); } - Assistant
This issue might be caused due to asynchronous code execution.
appHomeOpenedCallbackandjoinDayCallbackare both asynchronous functions, which allows other tasks to run while waiting for some of their tasks to complete. It's possible thatjoinDayCallbackis being called beforeappHomeOpenedCallbackhas calledsetUser.One way to ensure that the user exists in the store when using
joinDayCallbackis to change how you get the user. Instead of directly calling , create an async function that waits for the user to be set in the store. - User
When updating views with slack bolt my redux store is being reset
- Assistant
It seems like the Redux store is being reset due to the nature of Slack Bolt's execution. Each interaction (like opening a view, button click, or slash command) likely creates a new instance of your app, which might cause your Redux store to reset.
In this case, using the Redux store for managing users might not be a suitable solution because of the stateless nature of the Slack Bolt app instances. Instead, consider using another approach like caching to store the user data.
For example, you can use a simple in-memory cache:
- Create an in-memory cache object:
const userCache = new Map();- Update your
appHomeOpenedCallbackfunction to cache the user in theuserCacheobject:
userCache.set(slackId, userModified);- In your
joinDayCallback, first, attempt to retrieve the user from the cache. If the user is not present in the cache, fetch the user from the database: