Action not being fired - react-redux counter example - javascript

I'm trying to setup up my react project with redux and I'm following a basic example with a counter, which I can increment and decrement. The counter displays correctly on the page as 0 initially - however when I hit the button, the increment action doesn't seem to be dispatched, and as a consequence, the counter does not update.
My LoginPage.js:
/* eslint-disable no-unused-expressions */
import { connect } from "react-redux";
import React, { Component } from "react";
import { selectCounter } from "./../../selectors/counter";
import { actions as counterActions } from "./../../actions/counter";
class LoginPage extends Component {
componentDidMount() {}
render() {
const { counter, increment } = this.props;
return (
<div>
<p>{`Hi ${counter}`}</p>
<button onClick={() => increment()}>+</button>
</div>
);
}
}
LoginPage = connect(
(state, props) => ({
counter: selectCounter(state, props)
}),
{ ...counterActions }
)(LoginPage);
export default LoginPage;
My actions/counter.js:
import { INCREMENT } from "./../types/counter";
const increment = () => {
return { type: INCREMENT };
};
export const actions = {
increment
};
My /reducers/counter.js:
const { INCREMENT, DECREMENT } = "./../types/counter";
const counterReducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
module.exports = { counterReducer };
My /reducers/index.js:
import { combineReducers } from "redux";
import { counterReducer } from "./counter";
const rootReducer = combineReducers({
counter: counterReducer
});
export default rootReducer;
I'm omitting the App.js and index.js files as these are pretty simple and don't seem to be related to the problem.
UPDATE:
My actions/counter.js:
import { INCREMENT } from "./../types/counter";
import { useDispatch } from "react-redux";
const increment = () => {
return { type: INCREMENT };
};
const mapDispatchToProps = dispatch => {
return {
increment: () => dispatch(increment())
};
};
export const actions = {
...mapDispatchToProps(useDispatch)
};
Now I am seeing the bug:
react-dom.development.js:14724 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Updated
Need to properly define mapDispatchToProps function and pass it to connect(). In your code increment() doesn't seem to dispatch an action.
const mapDispatchToProps = (dispatch) =>{
increment: ()=>dispatch(actions.increment())
}
LoginPage = connect(
(state, props) => ({
counter: selectCounter(state, props)
}),
mapDispatchToProps
)(LoginPage);
Update
The error is due to useDispatch() usage outside component. It has to be declared and used within a functional component.

Related

React-Redux Class Component mapStateToProps error

Not able to access the redux store current state in a Class component.
It shows up console error
Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
When I tried to implement the same using a function component with useSelector and useDispatch, everything works as expected. What has gone wrong over here?
reducer.js
let initialState={
count:0
}
const reducer=(state=initialState,action)=>{
switch(action.type){
case ADD_INCREMENT:
return {
...state,
count:state.count+1
};
default: return state;
}
}
export default reducer;
action.js
const Increment=()=>{
return {
type:ADD_INCREMENT
}
}
store.js
import reducer from './reducer';
const store=createStore(reducer);
export default store;
Class Component
import { connect } from 'react-redux';
const mapStateToProps=state=>{
return {
count:state.count
}
}
const mapDispatchToProps=(dispatch)=>{
return {
count:()=>dispatch(action.Increment())
}
}
class Orders extends Component {
render() {
return (
<div>
<h1>Count: {this.props.count} </h1>
</div>
);
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Orders);
In App.js the entire container is wrapped with Provider and store is passed as props
Issue
You've named your state and your action both count, the latter is the one injected as a prop.
const mapStateToProps = state => {
return {
count: state.count // <-- name conflict
}
}
const mapDispatchToProps = (dispatch) => {
return {
count: () => dispatch(action.Increment()) // <-- name conflict
}
}
Solution
Provide different names, count for the state, maybe increment for the action.
const mapStateToProps = state => ({
count: state.count,
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch(action.Increment())
})

Defining reset slectors for memoization across multiple component instances

I am looking to using the redux reselect lib to write my react-redux selectors. From the docs there is this section that describes how to write selectors that can be used by several component instances.
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
import { makeGetVisibleTodos } from '../selectors'
const makeMapStateToProps = () => {
const getVisibleTodos = makeGetVisibleTodos() // here
const mapStateToProps = (state, props) => {
return {
todos: getVisibleTodos(state, props)
}
}
return mapStateToProps
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
makeMapStateToProps,
mapDispatchToProps
)(TodoList)
export default VisibleTodoList
I am wondering if the differences in how the makeGetVisibleTodos selector is called(as shown below), has implications on how memoization works. will memoization still work?, if not, why?
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
import { makeGetVisibleTodos } from '../selectors'
const makeMapStateToProps = () => {
const mapStateToProps = (state, props) => {
return {
todos: makeGetVisibleTodos()(state, props) // and here
}
}
return mapStateToProps
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
makeMapStateToProps,
mapDispatchToProps
)(TodoList)
export default VisibleTodoList
That example will never memoize at all, because it's creating a new selector instance every time mapState runs.
The key to correctly using memoized selectors is:
Reuse the same selector instance multiple times
And keep passing it the same arguments
If you create a new selector instance, it has no cached values. If you have the same instance but pass it different values each time you call it, then the memoization never works.
For more details, see my post Using Reselect Selectors for Encapsulation and Performance.

React/Redux not rendering nextState

The common cause for my issue when researching this is mutating the state and not returning a new object of the state which causes redux to not recognize a change. However, this is not and has never been an issue and i'm well aware of it. I'm returning a new object. In the logger which you can see in the attached image it displays the successful api call resolved and the nextState is updated but never rendered. Refreshing the page acts exactly the same even though i expected to possibly need to do so upon initial landing to root page.
Component:
import pokemonReducer from '../../reducers/pokemon_reducer';
import PokemonIndexItem from './pokemon_index_item';
import {Route} from 'react-router-dom';
import PokemonDetailContainer from './pokemon_detail_container';
class PokemonIndex extends React.Component {
componentDidMount() {
this.props.requestAllPokemon();
}
render() {
const pokemon = this.props.pokemon;
return (
<section className="pokedex">
<Route path='/pokemon/:pokemonID' component={PokemonDetailContainer} />
<ul>{pokemon && pokemon.map(poke => <li>{poke.name}{poke.id}</li>)}</ul>
</section>
);
}
}
export default PokemonIndex;
and the container:
import {connect} from 'react-redux';
import { selectAllPokemon } from '../../reducers/selectors';
import PokemonIndex from './pokemon_index';
import { requestAllPokemon } from '../../actions/pokemon_actions';
const mapStateToProps = state => ({
pokemon: selectAllPokemon(state)
});
const mapDispatchToProps = dispatch => ({
requestAllPokemon: () => dispatch(requestAllPokemon())
});
export default connect(mapStateToProps, mapDispatchToProps)(PokemonIndex);
the reducer:
import { RECEIVE_ALL_POKEMON, RECEIVE_SINGLE_POKEMON} from '../actions/pokemon_actions';
const pokemonReducer = (initialState = {}, action) => {
Object.freeze(initialState);
switch(action.type) {
case RECEIVE_ALL_POKEMON:
return Object.assign({}, initialState, action.pokemon);
case RECEIVE_SINGLE_POKEMON:
let poke = action.payload.pokemon
return Object.assign({}, initialState, {[poke.id]: poke})
default:
return initialState;
}
};
export default pokemonReducer;
secondary reducer:
import { combineReducers } from 'redux';
import pokemonReducer from './pokemon_reducer'
const entitiesReducer = combineReducers({
pokemon: pokemonReducer,
});
export default entitiesReducer;
rootreducer:
import {combineReducers} from 'redux';
import entitiesReducer from './entities_reducer';
const rootReducer = combineReducers({
entities: entitiesReducer
});
export default rootReducer;
as requested here is the selectors defined in reducers folder
export const selectAllPokemon = (state) => {
Object.values(state.entities.pokemon);
};
export const selectSinglePokemon = (state) => {
Object.values(state.entities.pokemon)
};
and here is the actions created:
export const RECEIVE_ALL_POKEMON = "RECEIVE_ALL_POKEMON";
export const RECEIVE_SINGLE_POKEMON = "RECEIVE_SINGLE_POKEMON";
import * as APIUtil from '../util/api_util';
export const receiveAllPokemon = (pokemon) => (
{
type: RECEIVE_ALL_POKEMON,
pokemon
}
);
export const requestAllPokemon = () => (dispatch) => {
APIUtil.fetchAllPokemon()
.then(
pokemon =>
{ dispatch(receiveAllPokemon(pokemon));}
);
};
export const receiveSinglePokemon = data => (
{
type: RECEIVE_SINGLE_POKEMON,
data
}
);
export const requestSinglePokemon = id => (dispatch) => {
APIUtil.fetchSinglePokemon(id)
.then(pokemon => {dispatch(receiveSinglePokemon(pokemon));
return pokemon;});
};
nextstate showing in console
As you stated in your question, your redux state is getting properly set but your new state is never being rendered and I think this has to do with your selector. It looks to me that you forgot to return your computed state.
export const selectAllPokemon = (state) => {
Object.values(state.entities.pokemon);
};
// will return undefined
For returning your state you have two options:
Explicit return
export const selectAllPokemon = (state) => {
return Object.values(state.entities.pokemon);
};
Implicit return
export const selectAllPokemon = (state) => (
Object.values(state.entities.pokemon);
);
I refer to this article or look at the examples I created in playground to get a better unstanding of implicit and explicit return in arrow functions.

Unable to dispatch event in react-redux

I am new to redux, I am trying to dispatch action on click event of button in react component.
But i cant update state i have in reducer.
types.js
export const FETCH_USERS_SUCCESS='FETCH_USERS_SUCCESS';
action.js
import {FETCH_USERS_SUCCESS} from './types';
export const fetchUsersSuccess = () =>
{
return (
{
type:FETCH_USERS_SUCCESS,
payload:'natalie',
}
);
}
reducer.js
import {FETCH_USERS_SUCCESS} from './types';
const initialState={
users:'mike',
error:null,
}
const reducer =(state=initialState,action)=> {
switch(action.type){
case FETCH_USERS_SUCCESS:
return {
...state,
users:action.payload,
}
default: return state
}
}
export default reducer;
and this is my app.js
import React from 'react';
import './App.css';
import { connect } from 'react-redux'
import { fetchUsersSuccess } from './action';
class App extends React.Component {
render(){
return (
<div>
<h1>Hello {this.props.users}</h1>
<button type="button" value="submit" onClick={this.props.handleSubmit}>submit</button>
</div>
);
}
}
const mapStateToProps = state => {
return {
users:state.users
}
}
const mapDispatchToProps=dispatch=>{
return {
handleSubmit: () => {dispatch(fetchUsersSuccess)}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
I am able to display initial user once but clicking on button does not change state.
Can anyone suggest why i cant update user on click event in react-redux?
Thanks.
https://react-redux.js.org/using-react-redux/connect-mapdispatch#two-forms-of-mapdispatchtoprops
mapDispathToProps has two forms: object and function. Redux documentation recommend to use object. In your case.
const mapDispatchToProps = {
handleSubmit: fetchUsersSuccess,
};
Another approach is to return a dispatch function which will then return the action which is done by using redux-thunk middleware. It is normally used for async operations.
So, your fetchUsersSuccess should be
export const fetchUsersSuccess = (dispatch) =>
{
return function() {
dispatch(
{
type:FETCH_USERS_SUCCESS,
payload:'natalie',
}
);
}
}
ES6
export const fetchUsersSuccess = (dispatch) =>
() => dispatch(
{
type:FETCH_USERS_SUCCESS,
payload:'natalie',
}
);
And then at the component level, do a currying like this.
const mapDispatchToProps=dispatch=>{
return {
handleSubmit: fetchUsersSuccess(dispatch)
}
}
Now you can call the handleSubmit or bind them already.

Timer React + Redux. React don't dispatch action by timer (SetInterval) in ComponentDidMount

I'm trying to make a timer in my App with React + Redux.
So I have a component parent:
import React, { Component } from "react";
import { connect } from "react-redux";
import { compose } from "redux";
import QuestionCounter from "../question-counter";
import FinishButton from "../finish-button";
import TimeCounter from "../time-counter";
import PauseButton from "../pause-button";
import testFinished from "../../actions/test-finished";
import timerTick from "../../actions/timer-tick";
import setTimer from "../../actions/set-timer";
import totalWithEwStruct from "../hoc/total-with-ew-structure";
import withIndicators from "../hoc/with-indicators";
const Total = ({ total, testFinished }) => {
const { finishedCount, totalCount, isPaussed, timeLeft } = total;
return (
<div className="test-total">
<QuestionCounter
finishedCount={finishedCount}
totalCount={totalCount}
testFinished={testFinished}
/>
<FinishButton testFinished={testFinished} />
<TimeCounter
timeLeft={timeLeft}
testFinished={testFinished}
setTimer={setTimer}
timerTick={timerTick}
/>
<PauseButton isPaussed={isPaussed} />
</div>
);
};
const mapStateToProps = ({ total, loading, error }) => {
return { total, loading, error };
};
const mapDispatchToProps = {
testFinished,
setTimer,
timerTick
}
export default compose(
totalWithEwStruct(),
connect(mapStateToProps, mapDispatchToProps),
withIndicators()
)(Total);
I try use timerTick by timer in componentDidMount
import React, { Component } from "react";
export default class TimeCounter extends Component {
componentDidMount() {
const { setTimer, timerTick } = this.props;
let timer = setInterval(() => {
timerTick();
console.log("tick");
}, 1000);
setTimer(timer);
}
componentDidUpdate() {
const { timeLeft, testFinished } = this.props;
if (timeLeft <= 0) {
testFinished();
}
}
render() {
const { timeLeft } = this.props;
return (
<div className="question-counter__timeleft">
Времени осталось
<span className="question-counter__timer">{timeLeft}</span>
</div>
);
}
}
So I see "tick" - "tick" - "tick" in console, but React doesn't dispatch my timerTick() function to reducer.
I have tried log to console action.type for debugging, and there is no action of timerTick.
const timerTick = () => {
return {
type: "TIMER_TICK"
};
};
export default timerTick;
Its code of action.
I don't understand why it doesn't work.
Your Total component needs to take timerTick function from props which is the one that is linked with redux store as you have added it to mapDispatchToProps.
If you do not destructure it from props, the ccomponent will use the imported function which isn't an action created unless its passed to dispatch function
const Total = ({ total, testFinished }) => {
const { finishedCount, totalCount, isPaussed, timeLeft, timerTick } = total;
return (
<div className="test-total">
<QuestionCounter
finishedCount={finishedCount}
totalCount={totalCount}
testFinished={testFinished}
/>
<FinishButton testFinished={testFinished} />
<TimeCounter
timeLeft={timeLeft}
testFinished={testFinished}
setTimer={setTimer}
timerTick={timerTick}
/>
<PauseButton isPaussed={isPaussed} />
</div>
);
};
You need to add dispatch of timer tick inside timer tick component. Because child component not aware about the actions.
Please refer below link for more details:
https://itnext.io/dispatching-actions-from-child-components-bd292a51f176
Response
if your component is not connected to redux you won’t be able to dispatch any action.
What do I mean?
Example
import React from “react”;
import { connect } from “react-redux”;
class MyCom extensa React.Component {
componentDidMount () {
const { action } = this.props;
action();
}
render () {
.....
}
}
const toState = state => ({....});
const toDispatch = {
action
};
export default connect(toState, toDispatch)(MyCom);
Explains
Basically connect from ”react-redux” is a HOC a high order component that on javascript world: is none but a high order function. a function that return another function.

Categories