Example with redux-observable and redux-form for react-redux-promise-listener - redux-form

React-redux-promise-listener contains only example for usage with React Final Form.
What is the right way to use it with redux-forms and redux-observable?

I had some success with using it with redux-observable. Have you seen the setup linked. Helped me when I was working on doing something similar:
// createStore.js
...
import createReduxPromiseListener from 'redux-promise-listener';
const reduxPromiseListener = createReduxPromiseListener();
function createStoreWrapper(history, testMiddleware) {
const middleware = [
createRouterMiddleware(history),
createEpicMiddleware(rootEpic),
createRavenMiddleware(Raven, {
// Optionally pass some options here.
}),
reduxPromiseListener.middleware,
];
if (testMiddleware) middleware.push(testMiddleware);
const enhancers = [responsiveStoreEnhancer, applyMiddleware(...middleware)];
if (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined') {
enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__());
}
const initialState = getInitialState();
const enhancer = compose(...enhancers);
const store = createStore(rootReducer, initialState, enhancer);
addHandlers(store);
return store;
}
Also see my somewhat-related question stack post.

Related

Dynamic axios request url in Vue 3 Composables

I've tried this and it worked:
const posts = ref{[]}
const urlEndPoint = 'posts'
const getPosts = async () => {
let response = await axios.get('/api/'+urlEndPoint)
posts.value = response.data.data
}
but that one is not dynamic. My goal is to make the urlEndPoint value reactive and set from the components
then i tried this:
const urlEndPoint = ref([])
but I don't know how to send the value of urlEndPoint constant back from the component to the composables.
I tried these in my component:
const urlEndPoint = 'posts'
and
const sendUrlEndPoint = () => {
urlEndPoint = 'posts'
}
but none worked.
is there a way to accomplish this goal? like sending the component name to urlEndPoint value in composable or any other simple way.
Define a composable function named use useFetch :
import {ref} from 'vue'
export default useFetch(){
const data=ref([])
const getData = async (urlEndPoint) => {
let response = await axios.get('/api/'+urlEndPoint)
data.value = response.data.data
}
return {
getData,data
}
in your component import the function and use it like :
const urlEndPoint=ref('posts')
const {getData:getPosts, data:posts}=useFetch()
getPosts(urlEndPoint.value)

How to use SSR with Redux in Next.js(Typescript) using next-redux-wrapper? [duplicate]

This question already has an answer here:
next-redux-wrapper TypeError: nextCallback is not a function error in wrapper.getServerSideProps
(1 answer)
Closed 1 year ago.
Using redux with SSR in Next.js(Typescript) using next-redux-wrapper, but getting error on this line
async ({ req, store })
Says, Type 'Promise' provides no match for the signature '(context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>): Promise<GetServerSidePropsResult<{ [key: string]: any; }>>
Property 'req' does not exist on type 'Store<EmptyObject & { filterReducer: never; }, any> & { dispatch: unknown; }'.
Property 'store' does not exist on type 'Store<EmptyObject & { filterReducer: never; }, any> & { dispatch: unknown; }'
Here is my SSR code:-
export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(async ({ req, store }) => {
let { query } = req
let searchCategory = query.category?.toString().toLowerCase().replace(/ /g, "-");
const apolloClient = initializeApollo();
const response = await apolloClient.query({
query: GET_PRODUCT_BY_CATEGORY,
variables: {
numProducts: 10,
category: searchCategory
}
});
await store.dispatch(getProducts(response));
});
You're calling wrapper.getServerSideProps in a wrong way.
Try like the following:
export const getServerSideProps = wrapper.getServerSideProps(
store => async ({req, res, query}) => {
// do your stuff with store and req
}
);
If you're looking for a working demo, you can visit my old answer
This code base could help you. ("next": "10.1.3")
Try using getInitialProps instead of getServerSideProps.
This works in my case. Like code below:
Try
in _app.js
import { wrapper } from '/store';
function MyApp(props) {
const { Component, pageProps } = props;
...
return (
<Component {...pageProps} />
)
}
App.getInitialProps = async props => {
const { Component, ctx } = props;
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
//Anything returned here can be accessed by the client
return { pageProps: pageProps, store: ctx.store };
};
export default wrapper.withRedux(App);
store.js file:
const makeStore = props => {
if (!isEmpty(props)) {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
} else {
const { persistStore, persistReducer } = require('redux-persist');
const persistConfig = {
key: 'root',
};
const persistedReducer = persistReducer(persistConfig, reducer); // Create a new reducer with our existing reducer
const store = createStore(
persistedReducer,
bindMiddleware([thunkMiddleware])
); // Creating the store again
store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store;
}
};
// Export the wrapper & wrap the pages/_app.js with this wrapper only
export const wrapper = createWrapper(makeStore);
in your page:
HomePage.getInitialProps = async ctx => {
const { store, query, res } = ctx;
};

Can we use customHooks into redux Saga function

Following custom hooks as state selector and using that within "functional View" component.
Now, I need to use that in redux Saga function. Can we use that into Saga function or I have to use some other approach instead of using custom hooks into Saga function ?
export function useSelectAllEntries()
{
return useSelector(
({allEntries=[]}) =>[...allEntries],shallowEqual
);
}
export function useSelectFilteredByMakeEntries()
{
const selectAll = useSelectAllEntries();
return selectAll.filter(...);
}
export function useSelectFilteredByCreatorEntries()
{
const selectAll = useSelectAllEntries();
return selectAll.filter(...);
}
Instead of defining these as custom hooks, define them as selectors instead. Redux selectors may be freely shared between multiple different use-cases.
export const allEntriesSelector = ({ allEntries = [] }) => allEntries;
export const allEntriesFilteredByMakeEntriesSelector = state =>
allEntriesSelector(state).filter(...);
export const allEntriesFilteredByCreatorEntriesSelector = state =>
allEntriesSelector(state).filter(...);
Then, when you want to use them in a function component, just call useSelector:
function MyComponent() {
const entries = useSelector(allEntriesSelector);
const filteredByMake = useSelector(allEntriesFilteredByMakeEntriesSelector);
const filteredByCreator = useSelector(allEntriesFilteredByCreatorEntriesSelector);
return (...);
}
and when you want to use them within a saga:
import { select } from 'redux-saga/effects';
function* mySaga() {
const entries = yield select(allEntriesSelector);
const filteredByMake = yield select(allEntriesFilteredByMakeEntriesSelector);
const filteredByCreator = yield select(allEntriesFilteredByCreatorEntriesSelector);
}

Selector for React-Redux

To use selector, I tried to follow this URL reference: https://blog.isquaredsoftware.com/2017/12/idiomatic-redux-using-reselect-selectors/
One of the example is :
const selectSomeData = state => state.someData;
const selectFilteredSortedTransformedData = createSelector(
selectSomeData,
(someData) => {
const filteredData = expensiveFiltering(someData);
const sortedData = expensiveSorting(filteredData);
const transformedData = expensiveTransformation(sortedData);
return transformedData;
}
)
const mapState = (state) => {
const transformedData = selectFilteredSortedTransformedData(state);
return {
data: transformedData
};
}
Question: Within mapState we are calling selectFilteredSortedTransformedData and we are also passing State as parameter. However, the function itself is not taking any parameter, how does it work?
const selectFilteredSortedTransformedData = createSelector(
did you add mapState function in redux connect function ?? something like this.
export default connect(mapState)(Component)

Redux action ajax result not dispatched to reducer

I just get to experiment with Redux and I know that middleware is essential to make ajax calls. I've installed redux-thunk and axios package separately and tried to hook my result as a state and render the ajax result to my component. However my browser console displays an error and my reducer couldn't grab the payload.
The error:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
This is part of my code and how the middleware is hooked up:
//after imports
const logger = createLogger({
level: 'info',
collapsed: true,
});
const router = routerMiddleware(hashHistory);
const enhancer = compose(
applyMiddleware(thunk, router, logger),
DevTools.instrument(),
persistState(
window.location.href.match(
/[?&]debug_session=([^&]+)\b/
)
)
// store config here...
my action:
import axios from 'axios';
export const SAVE_SETTINGS = 'SAVE_SETTINGS';
const url = 'https://hidden.map.geturl/?with=params';
const request = axios.get(url);
export function saveSettings(form = {inputFrom: null, inputTo: null}) {
return (dispatch) => {
dispatch(request
.then((response) => {
const alternatives = response.data.alternatives;
var routes = [];
for (const alt of alternatives) {
const routeName = alt.response.routeName;
const r = alt.response.results;
var totalTime = 0;
var totalDistance = 0;
var hasToll = false;
// I have some logic to loop through r and reduce to 3 variables
routes.push({
totalTime: totalTime / 60,
totalDistance: totalDistance / 1000,
hasToll: hasToll
});
}
dispatch({
type: SAVE_SETTINGS,
payload: { form: form, routes: routes }
});
})
);
}
}
reducer:
import { SAVE_SETTINGS } from '../actions/configure';
const initialState = { form: {configured: false, inputFrom: null, inputTo: null}, routes: [] };
export default function configure(state = initialState, action) {
switch (action.type) {
case SAVE_SETTINGS:
return state;
default:
return state;
}
}
you can see the state routes has size of 0 but the action payload has array of 3.
Really appreciate any help, thanks.
It looks like you have an unnecessary dispatch in your action, and your request doesn't look to be instantiated in the correct place. I believe your action should be:
export function saveSettings(form = { inputFrom: null, inputTo: null }) {
return (dispatch) => {
axios.get(url).then((response) => {
...
dispatch({
type: SAVE_SETTINGS,
payload: { form: form, routes: routes }
});
});
};
}

Resources