Error in rootReducer with Invariant Violation - react-native

RootReducer is not working I tried fixing this problem in all possible ways still it is throwing an error of this sort
ERROR Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
I want this error to be fixed in my part of code if possible
This is my code of UserSlice.js there is no error in the path
import { createSlice } from "#reduxjs/toolkit";
const userSlice = createSlice({
name: "user",
initialState: {
email: "",
password: "",
},
reducers: {
setEmail: (state, action) => {
state.email = action.payload;
},
setPassword: (state, action) => {
state.password = action.payload;
},
},
});
export const { setEmail, setPassword } = userSlice.actions;
export default userSlice.reducer;`
This is the code of my store
import { configureStore } from "#reduxjs/toolkit";
import userReducer from "./reducers/userSlice";
export const store = configureStore({
reducer: {
user: userReducer,
},
});
Both the configureStore as well createStore is not working in react redux

Related

React-native redux-saga error: takeLatest$1 requires a saga parameter

I created an App with some components and using the redux-saga in the following component:
// AlphaScreen.js
import ... // react & react-native
import { useSelector, useDispatch } from 'react-redux';
import { getUser } from '../redux/ducks/user';
const AlphScreen = props => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getUser());
}, [dispatch]);
const users = useSelector((state) => state.user.user);
console.log(users);
return (
<View><Text>Blah</Text></View>
);
}
// redux/ducks/user.js
export const SET_USER = "SET_USER";
export const GET_USER = "GET_USER";
export const setUser = (user) => ({
type: SET_USER,
user // user: user
});
export const getUser = () => ({
tye: GET_USER
});
const initialState = {
user: undefined
};
const userReducer = (state = initialState, action) => {
switch(action.type) {
case SET_USER:
const {user} = action;
return {...state, user:user};
default:
return state;
}
};
export default userReducer;
// redux/defaultStore.js
import {applyMiddleware, combineReducers, createStore} from 'redux'
import createSagaMiddleware from "redux-saga";
import counterReducer from './ducks/counter'
import userReducer from './ducks/user';
import { watcherSaga } from './sagas/saga';
const reducer = combineReducers({
user: userReducer
});
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const store = createStore(reducer, applyMiddleware(...middlewares));
sagaMiddleware.run(watcherSaga)
export default store;
// redux/sagas/saga.js
import { takeLatest } from 'redux-saga/effects';
import { handleGetUsers } from './handlers/user';
import { GET_USER } from '../ducks/user';
export function* watcherSaga() {
yield takeLatest(GET_USER, handleGetUsers); //<- getting error takeLatest$1 requires a saga parameter
}
// redux/sagas/handlers/user.js
import { call, put } from "redux-saga/effects";
import { setUser } from "../../ducks/user";
import { requestGetUser } from "../requests/user";
export function* handleGetUser(action) {
try {
const response = yield call(requestGetUser);
const { data } = response;
yield put(setUser(data));
} catch (error) {
console.log(error);
}
}
// redux/sagas/request/user.js
import axios from 'axios'
const requestGetUser = () => {
return axios.request({
method: "get",
url:"https://jsonplaceholder.typicode.com/users"
});
}
export { requestGetUser };
But I have following error:
takeLatest$1 requires a saga parameter
at node_modules/#redux-saga/core/dist/io-1d6eccda.js:37:10 in check
at node_modules/#redux-saga/core/dist/redux-saga-effects.dev.cjs.js:386:2 in validateTakeEffect
at node_modules/#redux-saga/core/dist/redux-saga-effects.dev.cjs.js:402:22 in takeLatest$1
at src/redux/sagas/saga.js:6:10 in watcherSaga
at node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1161:17 in next
at node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1112:6 in proc
at node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:1371:19 in immediately$argument_0
at node_modules/#redux-saga/core/dist/redux-saga-core.dev.cjs.js:60:15 in immediately
at [native code]:null in runSaga
at src/redux/configureStore.js:16:0 in <global>
at App.js:7:0 in <global>
at node_modules/expo/AppEntry.js:3:0 in <global>
at http://192.168.1.154:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&minify=false:141908:3 in global code
The above error occurred in task watcherSaga
Any suggestions for fixing the error? Thanks
To me it looks like a typo, handleGetUsers vs handleGetUser :)

"export 'default' (imported as 'Vue') was not found in 'vue' (Vuex, Store)

I am new to Vue and I want to rebuild a existing CMS using Vue.
As I was building the authentication system, this error appeared:
WARNING Compiled with 1 warnings 17:16:12
warning in ./src/store/index.js
"export 'default' (imported as 'Vue') was not found in 'vue'
The browser-console is telling me this:
Uncaught TypeError: Cannot read property 'use' of undefined
at eval (index.js:10)
at Module../src/store/index.js (app.js:1337)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader-v16/dist/index.js?!./src/views/auth/Login.vue?vue&type=script&lang=js:2)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader-v16/dist/index.js?!./src/views/auth/Login.vue?vue&type=script&lang=js (app.js:974)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (Login.vue?vue&type=script&lang=js:2)
at Module../src/views/auth/Login.vue?vue&type=script&lang=js (app.js:1469)
My main.js file:
import App from './App.vue'
import { createApp } from 'vue'
import router from './router'
createApp(App).use(router).mount('#app')
My store/index.js file:
import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios'
Vue.use(Vuex)
axios.defaults.baseURL = 'https://[blablabla]/api'
export const store = new Vuex.Store({
state: {
access_token: window.localStorage.getItem('access_token') || null,
filter: 'all',
todos: []
},
getters: {
access_token: state => {
return state.access_token;
}
},
mutations: {
retreiveToken(state, token) {
state.access_token = token;
}
},
actions: {
authenticate(context, credentials) {
axios.post('/user/authenticate.php', { username: credentials.username, password: credentials.password })
.then(response => {
// const token = response.data.access_token
// localStorage.setItem('access_token', token)
// context.commit('retrieveToken', token)
console.log(response)
})
.catch(error => {
console.log(error)
})
}
}
})
My /views/auth/Login.vue script:
<script>
import { store } from '#/store'
export default {
name: 'Login',
data() {
return{
username: '',
password: ''
}
},
methods: {
login(){
store.dispatch('authenticate', {
username: this.username,
password: this.password
})
}
}
}
</script>
When i remove "Vue.use(Vuex)" the browser errors with:
[vuex] must call Vue.use(Vuex) before creating a store instance
Can someone tell me what is going on here?
Thanks!
The suggestion from vladimir was right.
It seems like I have mixed vue3 with vue2.
After switching to vue2 everything worked perfectly!

Use Vuex classic mode in Nuxt application

I'm rewriting Vue application to Nuxt architecture because we want SSR. However I don't want to rewrite Vuex store file which is:
import Vue from "vue";
import Vuex from "vuex";
import vuexI18n from "vuex-i18n/dist/vuex-i18n.umd.js";
import toEnglish from "../translations/toEnglish";
import toSpanish from "./../translations/toSpanish";
import toGerman from "./../translations/toGerman";
import toRussian from "./../translations/toRussian";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
currentLanguage: ''
},
mutations: {
changeLang: (state, response) => {
if(response) {
state.currentLanguage = response;
Vue.i18n.set(response);
console.log(response);
}
}
}
});
Vue.use(vuexI18n.plugin, store);
Vue.i18n.add("en", toEnglish);
Vue.i18n.add("es", toSpanish);
Vue.i18n.add("de", toGerman);
Vue.i18n.add("ru", toRussian);
export default store;
I know that Nuxt has some other approach to that but I really want to stick with above code. Unfortuenally I can't call mutation from my component by:
this.$store.commit('changeLang', lang)
it print error in console:
[vuex] unknown mutation type: changeLang
I also tried like this
this.$store.commit('store/changeLang', lang)
but error is same. How to fix it? Do I need to rewrite this vuex file in order to make it work?
I followed #Aldarund tips and changed above code to:
import Vue from "vue";
import Vuex from "vuex";
import vuexI18n from "vuex-i18n/dist/vuex-i18n.umd.js";
import toEnglish from "../translations/toEnglish";
import toSpanish from "./../translations/toSpanish";
import toGerman from "./../translations/toGerman";
import toRussian from "./../translations/toRussian";
const store = () => {
return new Vuex.Store({
state: () => ({
currentLanguage: ''
}),
mutations: {
changeLang: (state, response) => {
if (response) {
state.currentLanguage = response;
Vue.i18n.set(response);
console.log(response);
}
}
}
})
};
Vue.use(vuexI18n.plugin, store);
Vue.i18n.add("en", toEnglish);
Vue.i18n.add("es", toSpanish);
Vue.i18n.add("de", toGerman);
Vue.i18n.add("ru", toRussian);
export default store;
now error is
Uncaught TypeError: store.registerModule is not a function
It's probably because of Vue.use(vuexI18n.plugin, store);.
You need to use classic mode.
Classic (deprecated): store/index.js returns a method to create a
store instance
So it should look like this, no vuex use, on import of Vue. And it must be a function that crestr store, not plain vuex object
import Vuex from 'vuex'
const createStore = () => {
return new Vuex.Store({
state: () => ({
counter: 0
}),
mutations: {
increment (state) {
state.counter++
}
}
})
}
export default createStore
Docs https://nuxtjs.org/guide/vuex-store/#classic-mode
As for plugin e.g. vyexi18 you need to move that code into plugin file and get created store object from context https://nuxtjs.org/guide/plugins/
export default ({ store }) => {
Your vuex18initcode
}

Vuex module breaks on getters declaration part

The Vuex store was starting to get a bit crowded so I decided to break it into modules. However, the code breaks after compiling with the following error
Uncaught TypeError: Cannot read property 'customS' of null
This is my invitations module
export const state = {
customS: null };
export const getters = {
getInvitations: (state) => state.customS, };
export const mutations = {
setcustomS: (state, customS) => state.customS= customS};
and this is how I import it inside the store
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
// Load store modules dynamically.
const requireContext = require.context('./modules', false, /.*\.js$/);
const modules = requireContext.keys()
.map(file =>
[
file.replace(/(^.\/)|(\.js$)/g, ''),
requireContext(file),
]
)
.reduce((modules, [
name,
module,
]) => {
if (module.namespaced === undefined) {
module.namespaced = true;
}
return { ...modules, [name]: module, };
}, {});
console.log(modules);
export const store = new Vuex.Store({
plugins: [
createPersistedState(),
],
modules,
});
Project is using the laravel and vue combination. Thanks in advance.

redux-observable TypeError: Cannot read property 'type' of undefined

I have been trying to implement react server-side-rendering using next, and i am using the with-redux-observable-app example, the example works fine, but i would like to improve the project a little bit by doing
redux modular pattern
fractal project structure
If possible, i would like to implement stateless components
Because #2, i can no longer use react state lifecycle, to solve that i usually took advantage of react router onEnter props, but this suggest that i should use componentWillMount, which doesn't meet my #2 condition
I have put the project on github, with this particular problem committed on this branch
Here's the summary of what i did so far
to achieve #1
// ./redux/index.js
...
import rootEpics from './root/epics'
import rootReducers from './root/reducers'
export default function initStore(initialState) {
const epicMiddleware = createEpicMiddleware(rootEpics)
const logger = createLogger({ collapsed: true })
const middlewares = applyMiddleware(thunkMiddleware, epicMiddleware, logger)
return createStore(rootReducers, initialState, middlewares)
}
// ./redux/root/epics.js
import { fetchCharacterEpic, startFetchingCharactersEpic } from '../ducks/Character/epics'
const rootEpics = combineEpics(
fetchCharacterEpic,
startFetchingCharactersEpic,
)
export default rootEpics
// ./redux/root/reducers.js
import { combineReducers } from 'redux'
import Character from '../ducks/Character'
const rootReducers = combineReducers({
Character,
})
export default rootReducers
// ./redux/ducks/Character/index.js
import * as types from './types'
const INITIAL_STATE = {
data: {},
error: {},
id: 1,
}
const Character = (state = INITIAL_STATE, { type, payload }) => {
switch (type) {
case types.FETCH_CHARACTER_SUCCESS:
return {
...state,
data: payload.response,
id: state.id + 1,
}
case types.FETCH_CHARACTER_FAILURE:
return {
...state,
error: payload.error,
}
default:
return state
}
}
export default Character
// ./redux/ducks/Character/types.js
export const FETCH_CHARACTER = 'FETCH_CHARACTER'
export const FETCH_CHARACTER_SUCCESS = 'FETCH_CHARACTER_SUCCESS'
export const FETCH_CHARACTER_FAILURE = 'FETCH_CHARACTER_FAILURE'
export const START_FETCHING_CHARACTERS = 'START_FETCHING_CHARACTERS'
export const STOP_FETCHING_CHARACTERS = 'STOP_FETCHING_CHARACTERS'
// ./redux/ducks/Character/actions.js
import * as types from './types'
export const startFetchingCharacters = () => ({
type: types.START_FETCHING_CHARACTERS,
})
export const stopFetchingCharacters = () => ({
type: types.STOP_FETCHING_CHARACTERS,
})
export const fetchCharacter = id => ({
type: types.FETCH_CHARACTER,
payload: { id },
})
export const fetchCharacterSuccess = response => ({
type: types.FETCH_CHARACTER_SUCCESS,
payload: { response },
})
export const fetchCharacterFailure = error => ({
type: types.FETCH_CHARACTER_FAILURE,
payload: { error },
})
// ./redux/ducks/Character/epics.js
import 'rxjs'
import { of } from 'rxjs/observable/of'
import { takeUntil, mergeMap } from 'rxjs/operators'
import { ofType } from 'redux-observable'
import ajax from 'universal-rx-request'
import * as actions from './actions'
import * as types from './types'
export const startFetchingCharactersEpic = action$ => action$.pipe(
ofType(types.START_FETCHING_CHARACTERS),
mergeMap(() => action$.pipe(
mergeMap(() => of(actions.fetchCharacter())),
takeUntil(ofType(types.STOP_FETCHING_CHARACTERS)),
)),
)
export const fetchCharacterEpic = (action$, id) => action$.pipe(
ofType(types.FETCH_CHARACTER),
mergeMap(() => ajax({
url: 'http://localhost:8010/call',
method: 'post',
data: {
method: 'get',
path: `people/${id}`,
},
})
.map(response => actions.fetchCharacterSuccess(
response.body,
true,
))
.catch(error => of(actions.fetchCharacterFailure(
error.response.body,
false,
)))),
)
to achieve #2
// ./pages/index/container/index.js
import React from 'react'
import { connect } from 'react-redux'
import { of } from 'rxjs/observable/of'
import rootEpics from '../../../redux/root/epics'
import { fetchCharacter } from '../../../redux/ducks/Character/actions'
import Index from '../component'
const mapStateToProps = state => ({
id: state.Character.id,
})
const mapDispatchToProps = dispatch => ({
async setInitialCharacter(id) {
const epic = of(fetchCharacter({ id }))
const resultAction = await rootEpics(
epic,
id,
).toPromise()
dispatch(resultAction)
},
})
export default connect(mapStateToProps, mapDispatchToProps)((props) => {
props.setInitialCharacter(props.id)
return (<Index />)
})
// ./pages/index/component/index.js
import React from 'react'
import Link from 'next/link'
import Helmet from 'react-helmet'
import Info from '../container/info'
const Index = () => (
<div>
<Helmet
title="Ini index | Hello next.js!"
meta={[
{ property: 'og:title', content: 'ini index title' },
{ property: 'og:description', content: 'ini index description' },
]}
/>
<h1>Index Page</h1>
<Info />
<br />
<nav>
{/* eslint-disable jsx-a11y/anchor-is-valid */}
<Link href="/other"><a>Navigate to other</a></Link><br />
<Link href="/about"><a>Navigate to about</a></Link>
{/* eslint-enable jsx-a11y/anchor-is-valid */}
</nav>
</div>
)
export default Index
// ./pages/index/container/info.js
import { connect } from 'react-redux'
import Info from '../../../components/Info'
const mapStateToProps = state => ({
data: state.Character.data,
error: state.Character.error,
})
export default connect(mapStateToProps)(Info)
with those above, the fetch works fine, but...
i don't want the fetch to keep running, i want it to run just once onEnter.
As an attempt to achieve that, i wrote an epic called startFetchingCharactersEpic(), and an action called startFetchingCharacters(), and lastly add mergeMap(() => of(actions.stopFetchingCharacters())), at the end of fetchCharacterEpic() pipe arguments, with the following scenario in mind
dispatch actions.startFetchingCharacters(), in container
that will trigger startFetchingCharactersEpic()
that will do so until types.STOP_FETCHING_CHARACTERS
that will dispatch actions.fetchCharacter()
that will trigger fetchCharacterEpic()
that will dispatch actions.stopFetchingCharacters()
that will trigger #3
setInitialCharacter
// ./pages/index/container/index.js
const mapDispatchToProps = dispatch => ({
async setInitialCharacter(id) {
const epic = of(startFetchingCharacters())
const resultAction = await rootEpics(
epic,
id,
).toPromise()
dispatch(resultAction)
},
})
but by doing that i got TypeError: Cannot read property 'type' of undefined, the console doesn't give me enough information than saying that the error is coming from setInitialCharacter
Tried googling the issue, but found nothing related to my problem
UPDATE
I manage to make it work again based on #jayphelps' answer below, which brought me back to some of my original problems, which are
How to fully use stateless component without utilizing react state lifecycle, especially replacing onEnter
How to just call the fetchCharacterEpic just once on page load
but i guess these 2 worth another post, as i realized i am asking too many question on this post
Totally guessing here, but it's possible that the error is coming from the fact that you're dispatching a Promise here:
const resultAction = await rootEpics(
epic,
id,
).toPromise()
dispatch(resultAction)
Your question doesn't mention, but that means you must have middleware that intercepts that promise since redux (and redux-observable) only expected POJOs { type: string }.
It's also possible that the promise isn't resolving to anything other than undefined, in which case the ofType operator in your epics will choke because it only works on those POJO actions { type: string }.
Sorry I can't help more specifically, it's tough to follow what the intent is.
e.g. this await rootEpics(epic, id) seems odd as rootEpics is the root epic and expects the arguments to be (action$, store) and UI components should not directly call epics?