Importing redux action makes other actions undefined - reactjs

This is one of the strangest things I have ever seen. It makes absolutely no sense to me. The short version is I have a Redux action creator function. If I import this function into this one particular component file, it makes every function imported from its file undefined.
So, let's start with the file filterInputModal.actions.js. This contains my Redux action functions, created using redux-starter-kit:
export const showAddCategoryModal = createAction('showAddCategoryModal');
That is the function I've been working with. Now, this function has long since been imported into my ManageVideoFilters.js component:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { showAddCategoryModal } from 'store/filterInputModal/filterInputModal.actions';
const ManageVideoFilters = (props) => {
/* Component logic */
};
/* PropTypes and mapStateToProps */
const mapDispatchToProps = (dispatch) => bindActionCreators({
showAddCategoryModal: () => showAddCategoryModal() // Done this way to avoid passing in a payload, since certain default event payloads cause Redux to print console errors
});
export default connect(mapStateToProps, mapDispatchToProps)(ManageVideoFilters);
So far so good. Before we go and break everything, let's take a look at my filterInputModal.reducer.js Redux reducer, also created using Redux Starter Kit:
import { createReducer } from 'redux-starter-kit';
import { showAddCategoryModal } from './filterInputModal.actions';
const initialState = {}; // The initial state for the reducer goes here
const handleShowAddCategoryModal = (state) => {
/* handle updating the state */
return state;
};
const actionMap = {
[showAddCategoryModal]: handleShowAddCategoryModal
};
export default createReducer(initialState, actionMap);
The action map uses the action creator functions toString() as the key, and then I provide my own functions to handle updating the state. Again, at this point, everything is perfect. We will come back to the reducer in a sec, first let's break things.
Now we're going to my VideFileEdit.js component. If we add the following line to this component, everything breaks:
import { showAddCategoryModal } from 'store/filterInputModal/filterInputModal.actions';
So, how does it break?
The import of the showAddCategoryModal function in filterInputModal.reducer.js now is undefined.
Because the reducer is using the functions as the keys to handle actions, the reducer is no longer able to handle the action properly and update the state.
It gets weirder though. Here are some of the weird behaviors I'm seeing.
If I import this action into any other component, everything is fine. The import in the reducer is unchanged.
The import of the function in both ManageVideoFilters.js and VideoFileEdit.js is fine.
So, what can I try next? This is really strange and doesn't make any sense to me. I've never seen this before.

As the commenter said, the problem was recursive imports. My filterInputModal.reducer.js exported some constants, which were imported into my filterInputModal.actions.js. The actions from filterInputModal.actions.js were then imported into filterInputModal.reducer.js. Hence the recursive import.
I moved the constants into a new file, filterInputModal.constants.js, and viola, problem solved.

Related

Get state value without using useSelector

Is there any way of getting the state value without using useSelector with using it in React Component
import { superAdmin, zoneManager } from './navigations'
import { useSelector } from 'react-redux'
const access = useSelector(state => state.access)
return access
The Error I get is:
Invalid hook call. Hooks can only be called inside of the body of a
function component.
Which I get it but is there any other way of getting the store value without the use of useSelector
Thank You
To make the store accessible anywhere (for whatever reason), you first need to export the store from the file where you are making it:
// fileThatMakesStore.js
export const store = configureStore();
Then, back in your file, you can simply import the store and getState().
import { store } from 'fileThatMakesStore.js';
const someValue = store.getState().something;
const someValue = store.getState().someReducer.something; // If you have multiple reducers
Good to know: The store is just a simple JS object with three functions: subscribe(), dispatch(), getState().
You can use getState of store, like this:
const access = store.getState().access

How to import and call a react pure function which is using redux connect and its functions? (Only React functional components no classes)

Suppose I have a react pure function named SignIn() in One.js :
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {GoogleSignin, statusCodes} from '#react-native-community/google-signin';
import {getToken, saveToken} from '../actions/token';
const SignIn = async ({token, getToken, saveToken}) => {
const savedToken = await getToken();
console.log(token.loading, savedToken);
SignIn.propTypes = {
token: PropTypes.string.isRequired,
getToken: PropTypes.func.isRequired,
saveToken: PropTypes.func.isRequired,
};
};
const mapStateToProps = state => {
console.log('state : ', state);
return {
token: state.token,
};
};
export default connect(mapStateToProps, {saveToken, getToken})(SignIn);
I want to use this SignIn() function in another Two.js react file so that getToken() which is a redux function and other functions will be called inside file One.js and then i can use those functions inside file Two.js but the problem is because of redux connect, i am not able to export and use them. How can i import and use this kind of function inside Two.js file ?
connect function can only be implemented with react components that renders actual jsx, and for it to work you need to return jsx elements or null and call it like this <SignIn />.. in my opinion if you want to implement some logic with the use of redux, you can make a custom hook, implement useSelector or useDispatch inside it, and either return the data you want or just do your effect inside it then return nothing.
hope this helps.
here's an example from react-redux docs https://react-redux.js.org/api/hooks#usedispatch
What Worked for me was declaring the functions that i want to export inside the redux actions, so i created a new action for any function that i want to use. Make sure to make use of loading state of initial state otherwise functions can be called infinite times because of re-rendering.

How do I wait for 2 actions to dispatch another action

I'm looking for a way to dispatch an action once I know multiple actions have been dispatched. I know that I can do this now by storing some variables in store. But is there a better way of doing it (Saga, Discoverables) etc. I tried to go through their documentation, but couldn't understand if it can be used for this purpose.
E.g in the below code, I want to dispatch some action in middleware when I know that 2 required actions have dispatched
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {createStore, applyMiddleware} from 'redux'
import {Provider} from 'react-redux'
const dummyReducer = (state=null,action) => {
return state
}
const defaultAction1 = { type: 'DEFAULT_ACTION1'}
const requiredAction1 = { type: 'REQUIRED_ACTION1'}
const requiredAction2 = { type: 'REQUIRED_ACTION2'}
const middle = (store) => (next) => (action) => {
if(action.type === 'REQUIRED_ACTION1')
console.log('Required actions satisfied')
next(action)
}
const store = createStore(dummyReducer, applyMiddleware(middle))
store.dispatch(defaultAction1)
//Dispatch an action after 2 secs
setTimeout(store.dispatch.bind(null,requiredAction1),2000)
setTimeout(store.dispatch.bind(null,requiredAction2),4000)
class DummyComponent extends Component{
render(){
return(<h1> nothing to see here </h1>)
}
}
ReactDOM.render(<Provider store={store}>
<DummyComponent />
</Provider>,
document.getElementById('root')
);
You can do this in saga simply by:
yield all([
take(REQUIRED_ACTION1),
take(REQUIRED_ACTION2),
])
yield put({type: FINAL_ACTION})
Actions must be self-explanatory and complete, it's a good practice to dispatch actions with all the needed info in their payloads.
Another reason that you should always try is dispatching different actions based on their purposes and take advantage of Redux tooling to debug your application properly. Redux updates the states synchronously and this is actually an advantage of its design. That said you know when one action goes through all the reducers you will have the proper state to reflect the changes on your UI part.
If you rely on two actions you somewhat can't rely on a single source of the truth which is your action1 and action2. And this forces you to wait for both of these in a middleware and it turns your actions into effects and effects are used in a different context.

How to make a redux connected react component listen to actions dispatched outside of react

I've got an actions file
import keyMirror from 'keymirror';
export const actionTypes = keyMirror({
OPEN_LIGHTBOX: null,
CLOSED_LIGHTBOX: null
});
export const openLightbox = (closable = false) => ({
type: 'OPEN_LIGHTBOX',
payload: {lightboxOpen: true, lightboxClosable: closable}
});
and a reducer, I'm not going to put the code in here because it doesn't seem necessary. It is at any rate working.
I have a react component that says
module.exports = connect((state) => {
console.log('state change'); // eslint-disable-line no-console
console.log(state); // eslint-disable-line no-console
return {
findShopDomainData: state.findShopDomain
}
})(Autocomplete);
I can register state changes inside of the react component, I get the console log statements.
But I also have stuff outside of react that needs to call these redux actions. So I import into a JS file.
import { createStore } from 'redux';
import { findShopDomain } from 'path to reducer file happens here'
import { openLightbox } from 'path to action file'
then I
let reduxStore = createStore(findShopDomain);
reduxStore.dispatch(openLightbox(true));
If I do that action in my vanilla js file I get to the reducer, but the state change is never registered in my connected React Component. I'm supposing it's because the connect function probably turns it into a new reducer, and in essence I actually have two reducers siting around that won't be affecting each other.
At any rate I would really like some way to have reduxStore.dispatch(openLightbox(true)); in my vanilla js be registered by my react component.
Using global scope
window.store = createStore(findShopDomain);
window.store.dispatch(openLightbox(true))

React Redux Refresh issue

I am using react-redux and I am having a issue where I loose my redux state when the page is refreshed.
Now before I go further on that this is the scenario, which I may be messing up.
Question one: Can I connect to more than one layout?
I have a dashboard and a "app" layout. Both have separate layouts. I connect both in the same manner:
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../actions/actionCreators';
function mapStateToProps(state) {
return {
profile: state.profile,
child: state.child,
}
}
function mapDispachToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
const LayoutApp = connect(mapStateToProps, mapDispachToProps) (DashboardLayout);
export default LayoutApp;
The dashboard connects just fine. I am able to hit reducers when i need to and update the store, however the dashboard links to the app for certain parts of data manipulation for you to play with. When it links I get the data in props as expected, however as soon as any page refreshes within the app layouts I loose the props being sent by maptoprops.
I have tried to combine into one master layout however that seems to have the same affect. I have also tried to save to state immediately when i first receive data but that seems to be lost as well upon refresh which makes me think it is resetting it.
Summary:
- DashboardLayout (connects to redux)
- AppLayout (connects to redux) however after a page refresh it looses props to the Applayout and needed data is gone.
Get to know redux-persist
https://github.com/rt2zz/redux-persist
You can install it using
npm i --save redux-persist
persistStore is the function that allows you to persist store.
import {persistStore} from 'redux-persist'
and autoRehydrate is the action that is performed whenever the state needs to be rehydrated
import {autoRehydrate} from 'redux-persist'
following is the structure that may be useful.
import {compose, applyMiddleware, createStore} from 'redux'
import {persistStore, autoRehydrate} from 'redux-persist'
// add `autoRehydrate` as an enhancer to your store (note: `autoRehydrate` is not a middleware)
const store = createStore(
reducer,
undefined,
compose(
applyMiddleware(...),
autoRehydrate()
)
)
// begin periodically persisting the store
persistStore(store)
and then for your reducer
import {REHYDRATE} from 'redux-persist/constants'
//...
case REHYDRATE:
var incoming = action.payload.myReducer
if (incoming) return {...state, ...incoming, specialKey:
processSpecial(incoming.specialKey)}
return state
following are the methods which can be used to work out of redux-persist
persistor.pause() - pauses redux persist
persistor.resume() - resumes redux persist
persistor.purge() - deletes all persisted data
persistor.rehydrate() - calls reducer to rehydrate store
types of storage redux persist allows
// sessionStorage
import { persistStore } from 'redux-persist'
import { asyncSessionStorage } from 'redux-persist/storages'
persistStore(store, {storage: asyncSessionStorage})
// react-native
import {AsyncStorage} from 'react-native'
persistStore(store, {storage: AsyncStorage})
// web with recommended localForage
import localForage from 'localforage'
persistStore(store, {storage: localForage})
it is the most basic use redux-persist hope it helps.
You can connect to as many components as you want to same store properties - that's not issue. Just to note here, connect is listening for changes so when action changes store it would cause all components listening to changed store parts to re-render (or at least do computation and then compare shadowdom).
Store is stored only when running application - after page close/resfresh it's cleared.
There is good thread about persistence of store (eg. to local storage): Where to write to localStorage in a Redux app?
As mentioned in the previous answers storing the state in local storage is one possible solution however some other possible solutions are
Make sure your links use the Push API ie <Link to={"route"}/> (react-router) this will ensure the store is not removed between route changes
Set your initial state when you create your store
const rootReducer = combineReducers({
todos: todos,
visibilityFilter: visibilityFilter
});
const initialState = {
todos: [{id:123, text:'hello', completed: false}]
};
const store = createStore(
rootReducer,
initialState
);
This will hydrate your reduce store when it is initialized
There are some other libs/frameworks/boilerplates that you could use that also implement server rendering with will render the HTML to the page on the initial render and then load React once the DOM has loaded some of this libs are
Next.js,Electroide,react-redux-universal-hot-example
Going down this route will add significant complexity to your app so you should weigh up the pros and cons before embarking down this route
I had this problem, so as somebody mentioned here, i used the localStorage.
In my reducer, i did like this:
const exampleKey = "_exampleKey"
const INITIAL_STATE = {
example: JSON.parse(localStorage.getItem(exampleKey))
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'SET_TRUE':
localStorage.setItem( exampleKey, JSON.stringify(true));
return { ...state, example: true };
case 'SET_FALSE':
localStorage.setItem( exampleKey, JSON.stringify(false));
return { ...state, example: false};
default:
return state
}
Pointing INITIAL_VALUES.example to localStorage's item example ensure us to keep the correct value when the page reloads.
Hope it helps somebody.

Resources