React Native Error: undefined is not a function (evaluating - javascript

On writing my first RN application, I have got the below error message on executing the code,
"undefined is not a function (evaluating '_ConfigureStore2.default.dispatch(CategoryAction.categoryView())')"
ConfigureStore.js:
import {createStore, applyMiddleware} from 'redux';
import reducers from '../reducers';
import thunk from 'redux-thunk';
var middlewares = applyMiddleware(thunk);
export default function configureStore(initialState) {
return createStore(reducers, initialState, middlewares);
}
CategoryContainer.js:
import React, { Component } from 'react';
import stores from '../stores/ConfigureStore';
import * as CategoryAction from '../actions/CategoryAction';
stores.dispatch(CategoryAction.categoryView());
class CategoryContainer extends Component {
}
CategoryAction.js:
import * as actionTypes from './ActionTypes';
import AppConstants from '../constants/AppConstants';
export function categoryView() {
const categories = ['CATEGORY1', 'CATEGORY2'];
return {
type: "CATEGORY_VIEW",
categories: categories
};
}
CategoryReducer.js:
const initialState = {
categories:[],
}
export default function categoryReducer (state = initialState, action) {
switch (action.type) {
case CATEGORY_VIEW:
return Object.assign({}, state, {
categories: action.categories
});
}
}
Even i tried the below approach in CategoryContainer.js, but still got the same error,
import { categoryView } from '../actions/CategoryAction';
stores.dispatch(categoryView());
Kindly assist to solve the issue.

Give this a shot:
CategoryAction.js
export default class CategoryAction {
categoryView = () => {
const categories = ['CATEGORY1', 'CATEGORY2'];
return {
type: "CATEGORY_VIEW",
categories: categories
};
}
}
CategoryContainer.js
import React, { Component } from 'react';
import stores from '../stores/ConfigureStore';
import CategoryAction from '../actions/CategoryAction';
stores.dispatch(CategoryAction.categoryView());
class CategoryContainer extends Component {
}

On changing the ConfigureStore.js as below solves the issue.
import {createStore, applyMiddleware} from 'redux';
import reducers from '../reducers';
import thunk from 'redux-thunk';
/*var middlewares = applyMiddleware(thunk);
export default function configureStore(initialState) { //default is undefined
return createStore(reducers, initialState, middlewares);
}*/
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(reducers);
export default store;

Related

TypeError: store.getState is not a function. (In 'store.getState()', 'store.getState' is undefined how can i resolve this problem?

i want to cnnect redux-saga witdh react-native but this error keep happen...
TypeError: store.getState is not a function. (In 'store.getState()',
'store.getState' is undefined
Warning: Failed prop type: Invalid prop store of type function
supplied to Provider, expected object
this is my code
(index.js)
import {AppRegistry} from 'react-native';
import Root from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => Root);
(App.js)
import React from 'react';
import Store from './store/configureStore'
import {Provider} from 'react-redux';
import {App} from './src/index';
const Root = () => {
return (
<Provider store={Store}>
<App />
</Provider>
);
};
export default Root;
(src/index.js)
import React from 'react';
import Navigator from './Screens/Navigator';
import styled from 'styled-components/native';
const App = ({}) => {
return (
<Navigator/>
);
};
export {App};
(store/cofigurestore.js)
import { applyMiddleware, createStore, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducer from '../reducers';
import rootSaga from '../sagas';
const Store = () => {
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const enhancer = process.env.NODE_ENV === 'production'
? compose(applyMiddleware(...middlewares))
: composeWithDevTools(
applyMiddleware(...middlewares),
);
const store = createStore(reducer, enhancer);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
};
export default Store;
(reducer/index.js)
import { combineReducers } from 'redux';
import user from './user';
import post from './post';
// (이전상태, 액션) => 다음상태
const rootReducer = (state, action) => {
switch (action.type) {
// case HYDRATE:
// // console.log('HYDRATE', action);
// return action.payload;
default: {
const combinedReducer = combineReducers({
user,
post,
});
return combinedReducer(state, action);
}
}
};
export default rootReducer;
(sage/index.js)
import { all, fork } from 'redux-saga/effects';
import axios from 'axios';
import postSaga from './post';
import userSaga from './user';
export default function* rootSaga() {
yield all([
fork(postSaga),
fork(userSaga),
]);
}
please help me ......... i want to resolve this problem...... but i don't know how can i do that
In you App.js you should be passing the result of calling you Store function to the Provider and not the function itself.
const Root = () => {
return (
<Provider store={Store()}>
<App />
</Provider>
);
};

React Redux -> Map is not a function?

So I am learning how to use redux and redux persist and currently I stuck at a problem right now. Whenever I try to map my store's content, it throws an error saying TypeError: tasks.map is not a function and I don't really know why the problem is occuring. I've googled around and tried debugging it, also tried to re-write the code a couple of time but it was all to no avail. Here's my entire code:
rootReducer.js
import React from 'react'
let nextToDo = 0;
const task=[
{
}
]
const reducer =(state=task, action)=>
{
switch(action.type)
{
case 'add':
return[
...state,
{
name: 'new',
id: nextToDo+=1
}
]
default:
return state;
}
}
export default reducer
store.js
import reducer from './rootReducer'
import {applyMiddleware,createStore} from 'redux'
import logger from 'redux-logger'
import {persistStore, persistReducer} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
const persistConfig ={
key: 'root',
storage
}
export const persistedReducer = persistReducer(persistConfig, reducer)
export const store = createStore(persistedReducer, applyMiddleware(logger));
export const persistor = persistStore(store);
export default {store, persistor}
Index.js:
import React, {Component} from 'react'
import {createStore} from 'redux'
import reducer from './rootReducer'
import 'bootstrap/dist/css/bootstrap.min.css'
import {Button} from 'react-bootstrap'
import {store} from './store'
import {connect} from 'react-redux'
class Index extends Component {
render(){
const {tasks} = this.props
const add=()=>
{
store.dispatch(
{
type: 'add',
}
)
}
store.subscribe(()=>console.log('your store is now', store.getState()))
return (
<div>
{tasks.map(task=><div>{task.name}</div>)}
<Button onClick={()=>add()}></Button>
</div>
)
}
}
const mapStateToProps=(state)=>
{
return{
tasks: state
}
}
export default connect(mapStateToProps)(Index)
Try to declare state this way:
state = {
tasks: [{}]
}
Then, on Index.js, you can pass it to props by doing this:
const mapStateToProps=(state)=>
{
return {
tasks: state.tasks
}
}
And use it inside the Component with props.tasks

Logout React Reducer w/ History, State & Action Bug

Hey I've looked at a bunch of help files now and cant seem to get the issue solved. Most suggestions are using a different setup than I have. The main issue that the others dont have is the LOGOUT feature. Can you suggest another way to handle the LOGOUT?
Here is my index.js for "combine reducers":
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import { LOGOUT_USER } from '../constants/index';
/* App Reducer Files */
import app from './app/reducer';
import accountData from './account/reducer';
import employeeData from './employee/reducer';
import locationData from './location/reducer';
import googleData from './google/reducer';
import requestData from './request/reducer';
import menuItemData from './menuItem/reducer';
import orderData from './order/reducer';
/* Public Reducer Files */
import valorData from './valor/reducer';
const appReducer = history => combineReducers({
router: connectRouter(history),
app,
accountData,
employeeData,
locationData,
googleData,
requestData,
menuItemData,
orderData,
// Public
valorData,
});
const rootReducer = history => (state, action) => {
if (action.type === LOGOUT_USER) {
state = undefined;
}
return appReducer(history, state, action);
};
export default rootReducer;
And my store.js:
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { routerMiddleware } from 'connected-react-router';
import rootReducer from '../services';
import history from '../history';
const debugware = [];
if (process.env.NODE_ENV !== 'production') {
debugware.push(createLogger({
collapsed: true,
}));
}
export default function configureStore(initialState) {
const store = createStore(
rootReducer(history),
initialState,
compose(
applyMiddleware(
routerMiddleware(history),
thunkMiddleware,
...debugware,
),
),
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../services', () => {
const nextRootReducer = require('../services/index').default;
store.replaceReducer(nextRootReducer);
});
}
return store;
}
This was working before I upgraded to a new router version. Again the main issue is the LOGOUT. If I just export appReducer it works just fine but doesnt logout.
WOW. The moment I post it I try one more thing...
const rootReducer = history => (state, action) => {
if (action.type === LOGOUT_USER) {
state = undefined;
}
return appReducer(history)(state, action);
};
Why are you returning an undefined state? Instead, return
if (action.type === LOGOUT_USER) {
return{ ...state, user: [] }
}
It basically returns and empty array as user.

this.props.onFetchEventDetail is not a function in React js

'onFetchEventDetail' function can't be called on componentDidMount.It shows this.props.onFetchEventDetail is not a function. I have made actions,reducers,selectors and saga for this function, all i need is this function to be triggered. Code is as follows:
import React, {Component} from 'react';
import {compose} from "redux";
import './EventDetailPage.css';
import PropTypes from 'prop-types';
import {requestEventDetail} from "./actions";
import {makeSelectEventDetail} from "./selectors";
import {createStructuredSelector} from "reselect";
import reducer from "./reducer";
import saga from "./saga";
import {connect} from "react-redux";
import injectReducer from "utils/injectReducer";
import injectSaga from "utils/injectSaga";
export class EventDetail extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("eventdetail:::" + this.props.match.params.eventId);
this.props.onFetchEventDetail();
}
render() {
return (
<div>
...
</div>
);
}
}
EventDetail.propTypes = {
eventId: PropTypes.string,
onLoadFetchEventDetail: PropTypes.func,
};
export function mapDispatchToProps(dispatch) {
return {
onFetchEventDetail: evt =>
dispatch(requestEventDetail())
}
}
const mapStateToProps = createStructuredSelector({
eventDetail: makeSelectEventDetail()
});
const withConnect = connect(
mapStateToProps,
mapDispatchToProps
);
const withReducer = injectReducer({key: "eventDetailPage", reducer});
const withSaga = injectSaga({key: "eventDetailPage", saga});
export default compose(
withReducer,
withSaga,
withConnect
)(EventDetail);

Redux-Saga somehow reducer updates without going through the saga

I am new to the saga world. Although I have worked with thunk on react-native territory, I am very confused at the moment. I am trying to get the skeleton of my project going which I expect to get very large soon. With that in mind, I am trying to separate the logic into multiple files.
I have gotten the reducer to fire except it is not the way I want. I am not sure how it is even happening. My saga does not fire but my state updates. I see the console log from my reducer but nothing from the saga watcher function. What should I change?
Index.js
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { Provider } from 'react-redux'
import reducer from './reducers'
import rootSaga from './sagas'
import App from './App'
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(rootSaga)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("etlRootDiv"),
);
App.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import FileExtensionSelector from './components/FileExtensionSelector'
import { setFileExtension } from './actions'
class App extends Component {
constructor(props) {
super(props)
}
handleTypeSelect() {
console.log('handle more click');
this.props.setFileExtension('zip');
console.log(this.props);
}
componentWillReceiveProps(nextProps){
console.log(nextProps);
}
render() {
return (
<div>
<FileExtensionSelector onFileTypeSelect={this.handleTypeSelect.bind(this)} />
<div>{this.props.fileType} ...asdasd</div>
</div>
)
}
}
const mapStateToProps = ({ metaState }) => {
const { fileType } = metaState;
return { fileType };
};
const mapDispatchToProps = (dispatch) => ({
setFileExtension(ext) {
dispatch(setFileExtension(ext))
}
})
export default connect(mapStateToProps, mapDispatchToProps)(App)
reducers/index.js
import { combineReducers } from 'redux';
import metaState from './MetaStateReducer';
const rootReducer = combineReducers({
metaState,
})
export default rootReducer
reducers/metastatereducer.js
const INITIAL_STATE = {
fileType: null,
hasHeader: false,
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case 'SET_FILE_EXTENSION':
console.log('/// in set file reducer ///');
console.log(action);
// console.log({ ...state, ...INITIAL_STATE, fileType: action.payload });
return { ...state,...INITIAL_STATE, fileType: action.payload };
default:
return state;
}
}
actions/metaStateActions.js
function action(type, payload = {}) {
return { type, ...payload }
}
export const SET_FILE_EXTENSION = "SET_FILE_EXTENSION";
export const setFileExtension = (extension) => action( SET_FILE_EXTENSION, { payload: extension });
actions/index.js
export { setFileExtension, SET_FILE_EXTENSION } from './metaDataActions';
sagas/metastatesagas.js
import { take, put } from 'redux-saga/effects'
import { SET_FILE_EXTENSION } from '../actions';
function* watchFileExtension(ext) {
console.log(' --- in watch file ext ---');
const { extension } = yield take(SET_FILE_EXTENSION)
console.log(`set extension is ${extension}`);
// yield put({ type: 'SET_FILE_EXTENSION', payload: ext });
}
export const metaStateSagas = [
take("SET_FILE_EXTENSION", watchFileExtension),
]
sagas/index
import { all } from 'redux-saga/effects'
import { metaStateSagas } from './MetaStateSagas';
export default function* rootSaga() {
yield all([
...metaStateSagas,
])
}
redux-saga always passes an action along to the store before attempting to process itself. So, the reducers will always run before any saga behavior executes.
I think the error is that your metaStateSagas array needs to use takeEvery, not take, but I'm not entirely sure. Try that and see if it fixes things.

Categories