I'm trying to migrate my react app to next.js app.
I like redux-saga
I like routing in redux-saga logic
And I want to do routing in redux-saga logic as I used to do!
but I cannot figure out how to do this.
question is..
How to route with redux-saga logic in Next.js?
Is this bad practice doing this? I think putting routing logic on saga seems more reasonable. But I think it is not a popular way. Why it is not used by many people?
To help understanding my situations.
I usally do routing in react app like below
one of my saga logic as example
export function* deletePost(action) {
const { postId } = action;
//delete post
yield api.postApi.deletePost(postId);
//route page to home ("/")
yield put(actions.router.push("/"));
}
I used 'connected-react-router' to do this.
and actions.router is exported from below file.
import { routerActions as router } from "connected-react-router"
export { router }
And below is how I configured my redux store
import { applyMiddleware, compose, createStore } from "redux";
import createSagaMiddleware from "redux-saga";
import { routerMiddleware } from "connected-react-router";
import { createBrowserHistory } from "history";
import { composeWithDevTools } from "redux-devtools-extension";
import { createRootReducer } from "data/rootReducer";
import rootSaga from "data/rootSaga";
const history = createBrowserHistory();
const sagaMiddleware = createSagaMiddleware();
const rootReducer = createRootReducer(history);
const env = process.env.NODE_ENV;
let composeFn = composeWithDevTools;
if (env === "production") {
composeFn = compose;
}
export default function configureStore() {
const store = createStore(
rootReducer,
composeFn(applyMiddleware( sagaMiddleware, routerMiddleware(history)))
);
sagaMiddleware.run(rootSaga);
return { history, store };
}
Related
I am using micro frontend and I am trying to change the architecture of state. Instead of using single state and a combined reducer I am using individual state for individual micro frontend apps. And also I am using a global state for cross application communication. I want to make my global state as read only. How can I make my global state as read only since I am using redux toolkit provider.
import thunk from "redux-thunk";
import { createBrowserHistory } from "history";
import { routerMiddleware } from "connected-react-router";
import { applyMiddleware, compose, createStore } from "redux";
import logger from "redux-logger";
import createRootReducer from "./modules";
const history = createBrowserHistory();
// eslint-disable-next-line no-unused-vars
function configureStore(preloadedState: any) {
const enhancers = [];
const node_env =
(window._env_ && window._env_.NODE_ENV) || process.env.NODE_ENV;
if (node_env === "development") {
enhancers.push(applyMiddleware(logger));
}
const middleware = [thunk, routerMiddleware(history)];
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers
);
return createStore(createRootReducer(history), composedEnhancers);
}
const StoreService = {
history,
configureStore,
};
export default StoreService;
this is store service for global state
I'm building a simple Next.js website that consumes the spacex graphql API, using apollo as a client. I'm trying to make an api call, save the returned data to state and then set that state as context.
Before I save the data to state however, I wanted to check that my context provider was actually providing context to the app, so I simply passed the string 'test' as context.
However, up[on trying to extract this context in antoher component, I got the following error:
Error: The default export is not a React Component in page: "/"
My project is set up as follows, and I'm thinking I may have put the context file in the wrong place:
pages
-api
-items
-_app.js
-index.js
public
styles
next.config.js
spacexContext.js
Here's the rest of my app:
spaceContext.js
import { useState,useEffect,createContext } from 'react'
import { ApolloClient, InMemoryCache, gql } from "#apollo/client"
export const LaunchContext = createContext()
export const getStaticProps = async () => {
const client = new ApolloClient({
uri: 'https://api.spacex.land/graphql/',
cache: new InMemoryCache()
})
const { data } = await client.query({
query: gql`
query GetLaunches {
launchesPast(limit: 10) {
id
mission_name
launch_date_local
launch_site {
site_name_long
}
links {
article_link
video_link
mission_patch
}
rocket {
rocket_name
}
}
}
`
});
return {
props: {
launches: data.launchesPast
}
}
}
const LaunchContextProvider = (props) => {
return(
<LaunchContext.Provider value = 'test'>
{props.children}
</LaunchContext.Provider>
)
}
export default LaunchContextProvider
_app.js
import LaunchContextProvider from '../spacexContext'
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return (
<LaunchContextProvider>
<Component {...pageProps} />
</LaunchContextProvider>
)
}
export default MyApp
Any suggestions on why this error is appearing and how to fix it?
I am working on the application which is purely redux-saga, but as the application is growing, the number of files is also growing. To solve this issue I am trying to setup redux-starter-kit to my current application.
Here is my store configuration file index.js
import { configureStore, getDefaultMiddleware } from 'redux-starter-kit'
import rootReducer from '../reducers'
export const store = configureStore({
reducer: rootReducer,
middleware: [...getDefaultMiddleware()]
})
old set up for just redux-saga without redux-starter-kit
// import createSagaMiddleware from 'redux-saga'
// import { initSagas } from '../initSagas'
// import rootReducer from '../reducers'
// import { loadState, saveState } from './browserStorage'
// function configureStore () {
// const sagaMiddleware = createSagaMiddleware()
// const persistedState = loadState()
// const createdStore = createStore(
// rootReducer,
// persistedState,
// applyMiddleware(sagaMiddleware)
// )
// initSagas(sagaMiddleware)
// return createdStore
// }
// export const store = configureStore()
// store.subscribe(() => {
// saveState(store.getState())
// })
the problem:
when I set up the redux-starter-kit the old sagas are not working.
Long story short:
How can I set up my existing redux-saga application with redux-starter-kit, without disturbing the current saga files?
Thank you in advance.
redux-starter-kit does not include sagaMiddleware by default [1]. You'll need to add it to the middleware list and initialize the sagas yourself.
In your case I believe this should work:
import createSagaMiddleware from 'redux-saga'
import { configureStore, getDefaultMiddleware } from 'redux-starter-kit'
import rootReducer from '../reducers'
import { initSagas } from '../initSagas'
const sagaMiddleware = createSagaMiddleware();
export const store = configureStore({
reducer: rootReducer,
middleware: [...getDefaultMiddleware(), sagaMiddleware]
})
initSagas(sagaMiddleware);
[1] https://redux-starter-kit.js.org/api/getdefaultmiddleware
What is the correct way to plug redux-batched-actions into my existing Redux store? I am completely confused by the Redux middleware API.
Currently I am using redux-thunk and redux-little-router.
Here is the code source that creates my Redux store:
import { createStore, applyMiddleware, compose, combineReducers } from 'redux'
import thunk from 'redux-thunk'
import { routerForBrowser } from 'redux-little-router'
import reducers from './store'
import routes from './routes'
const { reducer, middleware, enhancer } = routerForBrowser({ routes })
// Combine all reducers and instantiate the app-wide store instance
const allReducers = combineReducers({ ...reducers, router: reducer })
// Build middleware (if devTools is installed, connect to it)
const allEnhancers = (window.__REDUX_DEVTOOLS_EXTENSION__
? compose(
enhancer,
applyMiddleware(thunk, middleware),
window.__REDUX_DEVTOOLS_EXTENSION__())
: compose(
enhancer,
applyMiddleware(thunk, middleware)))
// Instantiate the app-wide store instance
const initialState = window.initialReduxState
const store = createStore(
allReducers,
initialState,
allEnhancers
)
The redux-batched-actions documentation exposes two usages: enableBatching and batchDispatchMiddleware. Which one should I use in my case?
Answering my own question after the return of my expedition into the fabulous source code of redux, redux-thunk, redux-batched-actions, ...
The correct way to do it seems to be using batchDispatchMiddleware, like this:
import { batchDispatchMiddleware } from 'redux-batched-actions'
// ...
const allEnhancers = (window.__REDUX_DEVTOOLS_EXTENSION__
? compose(
enhancer,
applyMiddleware(batchDispatchMiddleware, thunk, middleware),
window.__REDUX_DEVTOOLS_EXTENSION__())
: compose(
enhancer,
applyMiddleware(batchDispatchMiddleware, thunk, middleware)))
Note: I don't know if I could dispatch batched thunks, though. I don't do that in my current application. Use at your own risk!
Is there any way to integrate redux with aws-appsync in react-native?
If there is can you give me hint or clue on how to do it? I'm having a hard time integrating it. Thank you in advance.
I think you should be able to connect your own redux store as is detailed in their documentation. Basically create your own and use connect(mapStateToProps, mapDispatchToProps) from react-redux to connect your components.
const MyComponent = props => <h1>HI!</h1>
const ReduxConnected = connect(mapStateToProps, mapDispatchToProps)(MyComponent)
const GraphQLConnected = graphql(gql`query { hi }`)(ReduxConnected)
And then at the root of your application have
import AWSAppSyncClient from "aws-appsync";
import { Provider as ReduxProvider } from 'react-redux'
import { graphql, ApolloProvider } from 'react-apollo';
import { Rehydrated } from 'aws-appsync-react';
import { createStore } from 'redux'
const client = new AWSAppSyncClient({...})
const store = createStore({...})
const ConnectedApp = () =>
<ApolloProvider client={client}>
<Rehydrated>
<ReduxProvider store={store}>
<App />
</ReduxProvider>
</Rehydrated>
</ApolloProvider>
I haven't had a chance to try this setup but I will soon and will edit with any findings. In the meantime here is a link showing how to build a full RN app with AppSync that uses MobX instead of Redux (https://github.com/dabit3/heard) that may also be a good place to start.