My toolbar component dispatches an action abortGame(). I see in the console that it reaches the action creator (text "ONE!" displayed on the console) but never the reducer (text "TWO!" never displayed).
What is wrong?
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import App from './App';
import reducer from './store/reducers/reducer';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
applyMiddleware(thunk)
));
const app = (
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>
);
ReactDOM.render(app, document.getElementById('root'));
reducer.js
import * as actionTypes from '../actions/actionTypes';
const initialState = {
score: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ABORT_GAME:
console.log('TWO');
return {
...state,
score: 0,
};
default:
return state;
}
};
export default reducer;
actionTypes.js
export const ABORT_GAME = 'ABORT_GAME';
actions.js
import * as actionTypes from './actionTypes';
export const abortGame = () => {
console.log('ONE!');
return {
type: actionTypes.ABORT_GAME
};
};
Toolbar.js (component)
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { abortGame } from '../../store/actions/actions';
const toolbar = (props) => (
<div>
<div onClick={props.onAbortGame}><Link to="/">MyApp</Link></div>
</div>
);
const mapDispatchToProps = dispatch => {
return {
onAbortGame: () => dispatch(abortGame)
};
};
export default connect(null, mapDispatchToProps)(toolbar);
You have just missed the function brackets while dispatching the action
const mapDispatchToProps = dispatch => {
return {
onAbortGame: () => dispatch(abortGame)
};
};
Just change this line onAbortGame: () => dispatch(abortGame) to onAbortGame: () => dispatch(abortGame())
abortGame is a action creator which is basically a function. So you need to call the function inside dispatch
You just passing the function name in dispatch not calling it exactly.
Just convert the dispatch(abortGame())
sandbox working link
Related
I have started learning react-redux and was trying out the same but somehow the props are getting returned as undefined after mapping. Sharing code flow:
Below is the detailed code giving a brief idea on each component used.
App.js:
import './App.css';
import CakeContainer from './redux/cakes/CakeContainer';
import React from 'react';
import { Provider } from 'react-redux';
import store from './redux/store';
function App() {
console.log(store.getState())
return (
<Provider store = {store}>
<div className="App">
<CakeContainer/>
</div>
</Provider>
);
}
export default App;
CakeContainer.js
import React from 'react'
import { connect } from 'react-redux'
import { buyCake } from './CakeAction'
function CakeContainer(props) {
return (
<div>
<h1>Cake Container !!</h1>
<h2>Number of cakes - {props.cake}</h2>
<button onClick = {props.buyCake}> buy cakes</button>
</div>
)
}
const mapStateToProps = (state) =>{
return {
cake: state.cakeQuant
}
}
const mapDispatchToProps = dispatch => {
return {
buyCake: () => dispatch(buyCake())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CakeContainer)
Action.js
import {BUY_CAKE} from './CakeTypes'
export const buyCake = () =>{
return{
type: 'BUY_CAKE'
}
}
Reducer:
Reducer where i am passing the initial state and action for further processing.
import { BUY_CAKE } from "./CakeTypes";
const initialState = {
cakeQunt : 10
}
const CakeReducer = (state = initialState, action)=>{
switch(action.type){
case 'BUY_CAKE': return {
...state,
cakeQunt: state.cakeQunt - 1
}
default: return state;
}
}
export default CakeReducer;
Store.js
Creating store and passing reducer details to it
[![import { createStore } from "redux";
import CakeReducer from './cakes/CakeReducer'
const store = createStore(CakeReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
console.log(store.getState())
export default store;][1]][1]
Image showing the props value as undefined:
[1]: https://i.stack.imgur.com/EjXU1.png
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>
);
};
I am new to react and redux and trying to dispatch states from store but unable to do so,
Please anyone help me to resolve the problem...
App.js
import React from "react";
import store from './reduxStore/store';
import { Provider } from 'react-redux';
import Sidebar from './Sidebar';
function App() {
return (
<div>
<Provider store={store}>
<Sidebar ></Sidebar>
</Provider>
</div>
);
}
export default (App);
This is my sidebar.js Component
import React, { useEffect } from 'react';
import { updatePageLinkActions } from "../../reduxStore/actions/updatePageLinkActions";
import { connect } from "react-redux";
const Sidebar = () =>{
useEffect(() => {
return updatePageLinkActions
}, [])
return (
<>
<ListItem button onClick={updatePageLinkActions}>
<ListItemIcon><Home></Home></ListItemIcon>
<ListItemText primary="Dashboard" />
</ListItem>
<ListItem button onClick={() => handleOpenPage("contact")}>
<ListItemIcon><AcUnit></AcUnit></ListItemIcon>
<ListItemText primary="Contact" />
</ListItem>
</>
)
}
const mapStateToProps = (state) => ({
updatePage: state.updatePage.pgLink
})
export default connect(mapStateToProps, { updatePageLinkActions })(SidebarItems);
Store Store.js
import { createStore, applyMiddleware, compose } from "redux";
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const middleWare = [thunk]
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleWare),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
)
)
export default store;
Root Reducer rootReducer.js
import { combineReducers } from 'redux';
import updatePageLinkReducer from './updatePageLinRreducer';
export default combineReducers({
updatePage: updatePageLinkReducer
});
Action updatePageLinkActions.js
import { UPDATE_PAGE_LINK } from "../actionTypes";
//import store from "../store";
export const updatePageLinkActions = dispatch => {
console.log("actions log ", dispatch.payload)
return dispatch({
type: UPDATE_PAGE_LINK,
payload: {pageLink : "Action_pageLink" }
})
};
Reducer updatePageLinkReducer.js
import { UPDATE_PAGE_LINK } from '../actionTypes';
const initialState = {
pgLink: []
};
// eslint-disable-next-line import/no-anonymous-default-export
export default function(state = initialState, action) {
switch (action.type) {
case UPDATE_PAGE_LINK:
console.log("Action called ")
return { ...state, pgLink: action.payload }
default:
return state;
}
}
I am unable to dispatch values from store,
Please somebody help me...
If you are using functional components I strongly recommend getting rid of using connect.
To get state from Redux store, you can use useSelector hook, and to dispatch an action, you can use useDispatch hook.
import { useDispatch, useSelector } from 'react-redux'
...
const dispatch = useDispatch()
const updatePage = useSelector(state => state.updatePage.pgLink)
const updatePageLinkActions = () => {
dispatch({
type: UPDATE_PAGE_LINK,
payload: {pageLink : "Action_pageLink" }
})
}
...
Your action creator is not defined properly.
It should be this:
export const updatePageLinkActions = () => dispatch => {
console.log("actions log ", dispatch.payload)
return dispatch({
type: UPDATE_PAGE_LINK,
payload: {pageLink : "Action_pageLink" }
})
};
My component is not rerendering after the store is changing.
I make sure that the store is actually changing by dropping him to the console with
store.subscribe() and console.log(store.getState()) but still the component is not rerendering again.
I will appreciate your help.
configureStore.js
import { createStore, combineReducers } from 'redux';
import home from '../reducers/home';
import favorites from '../reducers/favorites';
export default () => {
const store = createStore(combineReducers({
home,
favorites
}))
return store;
}
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './redux/store/configureStore';
import AppRouter from './router/AppRouter';
const store = configureStore();
const jsx = (
<Provider store={store}>
<AppRouter />
</Provider>
);
ReactDOM.render(jsx, document.querySelector('#root'));
home.js (reducer)
const homeDefaultState = {
name: 'someName'
}
export default (state = homeDefaultState, action) => {
switch (action.type) {
case 'CHANGE_NAME':
return {
...state,
name: 'otherName'
}
default:
return state;
}
}
home.js (action)
export const changeName = () => ({
type: 'CHANGE_NAME'
})
Home.js (component)
import React from 'react';
import configureStore from '../../redux/store/configureStore';
import { changeName } from '../../redux/actions/home';
import { connect } from 'react-redux';
const store = configureStore();
const handleName = () => {
store.dispatch(changeName())
}
const Home = (props) => (
<div className="home">
<button onClick={handleName}>
change name
</button>
{props.home.name}
</div>
);
const mapStateToProps = (state) => ({
home: state.home
});
export default connect(mapStateToProps)(Home);
In your Home component you initialize store for second time. And bound action to this second store
const store = configureStore();
const handleName = () => {
store.dispatch(changeName())
}
At the same time with connect() you access store declared in App.jsx
Read from first but update second. Just remove second store and use mapDispatchToProps(second parameter passed to connect()) instead:
const mapStateToProps = (state) => ({
home: state.home
});
export default connect(mapStateToProps, { handleName: changeName })(Home);
I cant figure out what is going on. I have redux-thunk setup just like always. For some reason that I can not figure out I get the error: Error: Actions must be plain objects. Use custom middleware for async actions. can anyone help me figure this error out?
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
CreateStore.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
export default function configureStore(initialState) {
return createStore(
reducers,
initialState,
applyMiddleware(thunk)
);
}
app.js
import React, { Component } from 'react';
import Routes from './Routes';
import {Provider} from 'react-redux';
import configureStore from './configureStore';
const store = configureStore();
class App extends Component {
render(){
return (
<Provider store={store}>
<Routes/>
</Provider>
);
}
}
export default App;
Today.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { autoLocate } from '../actions';
import { Button } from './Common'
class Today extends Component {
componentDidMount() {
this.props.fetchTodayWeather('http://
api.wunderground.com/api/cc9e7fcca25e2
ded/geolookup/q/autoip.json');
}
render() {
return (
<div>
<div style={styles.Layout}>
<div><Button> HAHAH </Button></div>
<div><Button> Weather Now </Button></div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
const loading = state.locate.loading;
const located = state.locate.autolocation;
return{ loading, located };
};
const mapDispatchToProps = (dispatch) => {
return {
fetchTodayWeather:(Url) => dispatch(autoLocate(Url))
};
};
export default connect(mapStateToProps,mapDispatchToProps)(Today);`
autoLocate.js
import { AUTODATA,
AUTOLOCATING
} from './types';
export const autoLocate = (url) => {
return (dispatch) => {
dispatch({ type: AUTOLOCATING });
fetch(url)
.then(data => fetchSuccess(dispatch, data))
};
};
const fetchSuccess = (dispatch, data) => {
dispatch({
type: AUTODATA,
payload: data
});
};