Trying to build up microfrontends with Webpack 5 Module Federation. Having an issues with fetching remote reducers from micro-app.
This is what I've tried, and it doesn't work.
const loadAppBReducers= import('app-b/reducers');
export const store = configureStore({
reducer: {
...(async () => (await loadAppBReducers).reducers)(),
},
});
Related
Say i have a store configured like so.
const buildStore = (formSettings) => {
// const isDevToolsRequired = process.env.NODE_ENV === 'development';
const sagaMiddleware = createSagaMiddleware();
const preloadedState = initialState(formSettings);
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => [
...getDefaultMiddleware({
thunk: false, // We use redux-saga i.e. objects, not the default, thunk i.e. callbacks
serializableCheck: false, // redux toolkit issues
immutableCheck: false, // TODO remove this if we can - after the full move to redux toolkit
}),
sagaMiddleware,
],
preloadedState,
devTools: true, // TODO turn off dev tools for prod once up and running
});
sagaMiddleware.run(rootSaga);
return store;
};
How do i get the preloadedState into initialState of an immerSlice in a next.js application? getStaticProps is used to get build time formSettings from another service, then its passed to configureStore... but i need that value (or parts of it) as my initial for the slices...
My rootReducer looks like:
const rootReducer = combineReducers({
components,
legalStatement,
navigation,
optionalFormConfig,
paging,
formConfig,
submission,
submissionStatus,
});
Removing initialState from any of the slices causes a runtime error, but anything added to initialState does not show in redux state.... my interpretation is that the initialState in the slice is overwritten as i provide preloadedState... so why is the initialState in the slice a required field?
I have a React app where I've used the #rtk-query/codegen-openapi tool to generate my authentication queries and mutations. I'm also using Redux Persist to store some of this data.
I'm trying to figure out a way to invalidate this data programmatically when the user logs out. Is it possible to do this?
My redux store configuration looks something like this:
const persistConfig = {
key: "root",
storage,
blacklist: ["api"],
};
const authPersistConfig = {
key: "auth",
storage,
whitelist: [],
};
const rootReducer = combineReducers({
settings: settingsSlice.reducer,
[applicationApi.reducerPath]: applicationApi.reducer,
[enhancedAuthenticateApi.reducerPath]: persistReducer(
authPersistConfig,
enhancedAuthenticateApi.reducer
),
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const buildStore = () =>
configureStore({
reducer: persistedReducer,
middleware: getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}).concat([enhancedAuthenticateApi.middleware]),
});
I'm pretty new to Redux and RTK Queries so any help is appreciated.
I am trying to connect redux-state-sync for syncronize state in different tabs to my next-redux project. But I have a server error (TypeError: dispatch is not a function) in this line: initStateWithPrevTab(makeStore). So how can I fix this bug? I try to add initStateWithPrevTab(makeStore) as a const or inside arrow func, but it still doesn't work. It's my store.js file where I configure store:
const config = {};
const middlewares = [createStateSyncMiddleware(config)];
const rootReducer = combineReducers({
booking: reducer,
});
const makeStore = () =>
createStore(
withReduxStateSync(rootReducer),
undefined,
applyMiddleware([config])
);
initStateWithPrevTab(makeStore);
export const wrapper = createWrapper(makeStore, { debug: true });
I'm trying to implement redux-toolkit in my Next.js project without losing the option of SSR for the data I'm fetching from an external API. I have followed the example in next.js GitHub but doing so led to not having SSR when fetching data in my redux slice. I would like to know how I can fetch data and save that data in the Redux state. this is what I've written:
this is the store.js file
export const store = configureStore({
reducer: {
users: usersReducer,
},
});
the _app.js file
import { Provider } from 'react-redux';
import { store } from '../app/store';
const MyApp = ({ Component, pageProps }) => {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
};
export default MyApp;
the usersSlice.js file
import { createSlice, createAsyncThunk } from '#reduxjs/toolkit';
const initialState = {
items: null,
status: 'idle',
error: null,
};
export const fetchUsers = createAsyncThunk('users/fetchUsers', async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await res.json();
return users;
});
const usersSlice = createSlice({
name: 'categories',
initialState,
reducers: {},
extraReducers: {
[fetchUsers.pending]: (state, action) => {
state.status = 'loading';
},
[fetchUsers.fulfilled]: (state, action) => {
state.status = 'succeeded';
state.items = action.payload;
},
[fetchUsers.rejected]: (state, action) => {
state.status = 'failed';
state.error = action.error.message;
},
},
});
export default usersSlice.reducer;
and finally where the page I'm fetching the data from:
export default function Home() {
const dispatch = useDispatch();
const users = useSelector((state) => state.users.items);
useEffect(() => {
dispatch(fetchUsers());
}, [dispatch]);
return (
<div>
<h1>users</h1>
{users &&
users.length &&
users.map((user) => <p key={user.id}>{user.name}</p>)}
</div>
);
}
If I fetch data through dispatching the fetchUsers function it won't have SSR, and if I use getServerSideProps it won't be saved in redux state. I'm clueless
If you are okay to use Redux instead of redux-toolkit then follow this example
[https://github.com/vercel/next.js/blob/canary/examples/with-redux-persist]Officail Example form Vercel/next.js. I too facing some issue when i am writing SSR code for Redux persist with redux toolkit. The work is currently in progress. Will share the code when it is available. Sis
I'm trying to set locations into a Vuex store in my Nuxt app. I've looked into using vuexfire, however, I'm unsure if this would be optimal in a SSR app or generally what is the most simple best practice.
How do you request from firebase firestore and set the state (of the 'locations' in this example)?
Would it be best to use nuxtServerInit in a SSR app?
store/index.js
import Vuex from 'vuex'
import firebase, {auth, db} from '#/services/firebaseinit.js'
const createStore = () => {
return new Vuex.Store({
state: {
user: null,
locations: [],
},
getters: {
// User
activeUser: (state) => {
return state.user
},
// Locations
loadedLocations(state) {
return state.loadedLocations
}
},
mutations: {
// User
setUser (state, payload) {
state.user = payload
},
// Locations
setLocations (state, locations) {
state.locations = locations
}
},
actions: {
// Locations
setLocations(vuexContext, locations) {
vuexContext.commit('setLocations', locations)
},
// Users
autoSignIn ({commit}, payload) {
commit('setUser', payload)
},
signInWithFacebook ({commit}) {
return new Promise((resolve, reject) => {
auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
resolve()
})
},
signOut ({commit}) {
auth.signOut().then(() => {
commit('setUser', null)
}).catch(error => console.log(error))
},
}
})
}
I haven't used vuexfire but have used firebase with nuxt and it works pretty well. this is what I did.
npm install --save firebase
create a file called firebase.js and put this sort of code in it:
import * as firebase from 'firebase'
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: '<your-api-key>',
authDomain: '<your-domain>',
databaseURL: '<your-url>',
projectId: '<your-id>',
storageBucket: '<your-bucket>'
})
}
export { firebase }
then you register that file as a plugin in nuxt.config.js
plugins: [
'#plugins/firebase.js'
],
You need to import firebase at the top of your index.js (or other file you're using it in) in the store.
import * as firebase from 'firebase'
then you can use firebase in your nuxtServerInit as you want. Eg.
actions: {
nuxtServerInit({dispatch}, context) {
return Promise.all([
dispatch('get_posts', context),
dispatch('any_other_actions', context)
]);
},
get_posts (vuexContext, context) {
return firebase.database().ref(YOUR DB).once('value')
.then(res => {
//...What you want it to do here
})
},
Firebase is pretty powerful and you'll want to read the docs for specifics about the functions you want to perform but yeah, goes good in nuxt.