Dispatch an action in redux - redux

I created an app which should simulate the buying of products. So, when i will click on the BUY button, the number of fruits should decrement.
I suppose that the problem is in my reducer, but i can' t understand where.
/////
const Fruits = (props) => {
console.log(props);
return (
<div>
<h1>Number of fruits: {props.numFruits} </h1>
<button onClick={buyFruitsAction}>BUY</button>
</div>
);
};
const mapStateToProps=(state)=> {
return {
numFruits: state.numFruits
}
};
const mapDispatchToProps=(dispatch)=> {
return {
buyFruitsAction: ()=> dispatch(buyFruitsAction())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Fruits)
//// Reducer
import {BUY_FRUITS} from "../types";
const initialState = {
numFruits : 10
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case BUY_FRUITS : return {
...state,
numFruits: state.numFruits - 1
};
default: return state;
}
};
export default reducer;
Where is the issue of my code?

This line is the problem:
<button onClick={buyFruitsAction}>BUY</button>
There is no variable buyFruitsAction, it is a property. So that should read props.buyFruitsAction.

Your reducer is fine, can you post your action creator?
buyFruitsAction is undefined in your component do you meant props.buyFruitsAction?

Related

TypeError: dispatch is not a function when clicking the toggle button

I am using react redux-thunk. I have a set of users data that I get from an API and this is the schema:
.
I've connected the "active" property with the checked attribute of a Switch MUI button, so naturally when calling the API I have some users with their switch button already on "true". What I am trying to do is to just make the switch functional, and just be able to click it and change its state, not necessarily doing anything with that.
Here's my toggleType.js:
export const TOGGLE = "TOGGLE";
Here's my toggleAction.js:
import { TOGGLE } from "./toggleType";
const statusToggleAction = () => {
return {
type: TOGGLE,
};
};
export const statusToggle = () => {
return (dispatch) => {
dispatch(statusToggleAction);
};
};
Here's my toggleReducer.js:
import { TOGGLE } from "./toggleType";
const initialState = {
status: false,
};
const toggleReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE:
status: true;
default:
return state;
}
};
export default toggleReducer;
Everything is under my userContainer.js, like that:
function UserContainer({ userData, fetchUsers }) {
useEffect(() => {
fetchUsers();
}, []);
return userData.loading ? (
<h2>Loading</h2>
) : userData.error ? (
<h2>{userData.error}</h2>
) : (
<Container maxWidth="lg" style={{ flexGrow: 1, height: "100%" }}>
<h2>User List</h2>
<div>
{userData &&
userData.users &&
userData.users.map((user) => (
<div key={user.id}>
<p>{user.name}</p>
<Switch checked={user.active} onChange={statusToggle()} />
</div>
))}
</div>
</Container>
);
}
const mapStateToProps = (state) => {
return { userData: state.user, statusToggle: state.status };
};
const mapDispatchToProps = (dispatch) => {
return {
fetchUsers: () => dispatch(fetchUsers()),
statusToggle: () => dispatch(statusToggle()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserContainer);
This is the error I am getting whenever I am clicking one of those switches:
Any ideas are welcome, I "learned" redux like 3 days ago!
toggleReducer function in toggleReducer.js, replace status: true; with return { status: true }.
Just return action in statusToggle function in toggleAction.js without dispatch as following.
export const statusToggle = () => {
return statusToggleAction();
};
Or just call statusToggleAction directly in userContainer.js as following.
export const statusToggle = () => {
return (dispatch) => {
dispatch(statusToggleAction());
};
};

Why is my method not working? react-redux

I am studying react-redux. First of all, the action of addTodo looks like this.
let nextTodoId = 0;
export const addTodo = (content) => ({
type: ADD_TODO,
payload: {
id: ++nextTodoId,
content
}
});
And the component is here
import React, { useState } from "react";
import { connect } from "react-redux";
import { addTodo } from "../redux/actions";
function AddTodoComponent(props) {
const [inputValue, setInput] = useState("");
console.log({ addTodo })
const handleAddTodo = () => {
console.log(inputValue)
props.addTodo(inputValue);
setInput("");
};
return (
<div>
<input onChange={(e) => setInput(e.target.value)} />
<button className="add-todo" onClick={handleAddTodo}>
Add Todo
</button>
</div>
);
}
export default connect(null, { addTodo })(AddTodoComponent);
I want to use mapStateToProps and mapDispatchToProps but It's not working.
I thought It will be work if I use destructing object.
But it's not appear in console too.
Am I wrong?
import React, { useState } from "react";
import { connect } from "react-redux";
import { addTodo } from "../redux/actions";
function AddTodo({
allId,
byId,
newTodo,
}) {
const [inputValue, setInput] = useState("");
const handleAddTodo = () => {
newTodo(inputValue);
setInput("");
};
return (
<div>
<input onChange={(e) => setInput(e.target.value)} />
<button className="add-todo" onClick={handleAddTodo}>
Add Todo
</button>
</div>
);
}
const mapStateToProps = state => {
return {
allId: state.allId,
byId: state.byId,
}
}
const mapDispatchToProps = dispatch => {
return {
newTodo: () => dispatch(addTodo()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AddTodo);
and this is reducer function.
import { ADD_TODO, TOGGLE_TODO } from "../actionTypes";
const initialState = {
allIds: [],
byIds: {}
};
export default function(state = initialState, action) {
switch (action.type) {
case ADD_TODO: {
const { id, content } = action.payload;
return {
...state,
allIds: [...state.allIds, id],
byIds: {
...state.byIds,
[id]: {
content,
completed: false
}
}
};
}
case TOGGLE_TODO: {
const { id } = action.payload;
return {
...state,
byIds: {
...state.byIds,
[id]: {
...state.byIds[id],
completed: !state.byIds[id].completed
}
}
};
}
default:
return state;
}
}
It took me a bit of playing but I found your problem! (3 problems, actually).
Your addTodo function is a function which takes the content of the Todo (a string) and creates the action.
const mapDispatchToProps = (dispatch) => {
return {
newTodo: () => dispatch(addTodo())
};
};
But in your mapDispatchToProps function, you are accepting no arguments and calling addTodo with no arguments. So your Todo gets added, but the content will always be undefined.
Change this to
newTodo: (content) => dispatch(addTodo(content))
In mapStateToProps you've got a misnamed property. You need to change state.byId to state.byIds.
In order to clear the content of the input, you need the value of the input to be controlled by your useState. Add value={inputValue} to the input element.
<input value={inputValue} onChange={(e) => setInput(e.target.value)} />
This is a sidenote, but you might want to think about learning typescript and adding annotations to your projects. There is a bit of a learning curve but the tradeoff is you would be able to catch things like missing arguments and misnamed properties easily. They can be a real head-scratcher otherwise.

I was trying to get input with redux,all is fine but I can't figure out how to get input values

Trying to get user input with action,all is working i get my console.logs about how inputVal changes,but when I try to print this in i get undefined in console
Should I use like mapDispatchToProps or I don't need this,since I'm passing actions as second param into mapStateToProps
actions:
export const inputChange = val => {
return {
type: INPUT_CHANGE,
payload: val
};
};
reducer:
import { INPUT_CHANGE } from './actionTypes';
const initialState = {
inputVal: ''
};
export default (state = initialState, action) => {
switch (action.type) {
case INPUT_CHANGE:
return {
...state,
inputVal: action.payload
};
default:
return state;
}
};
mainPage:
const mapStateToProps = state => {
console.log(state);
return state;
};
class MainPage extends Component {
onInput = e => {
this.props.inputChange(e.target.value);
console.log(this.props.inputChange(e.target.value));
};
render() {
console.log(this.props.inputVal);
return (
<div>
<input onChange={this.onInput}></input>
<p>{this.props.}</p>
</div>
);
}
}
export default connect(
mapStateToProps,
{
addToCart,
removeFromCart,
selectItem,
inputChange
}
)(MainPage);
combinedReducers:
import { combineReducers } from 'redux';
import AddItem from './addItem/reducer';
import InputReducer from './reducerInput';
export default combineReducers({
AddItem,
InputReducer
});
I've tried to this.props.inputVal.
Since you have combineReducers, you should use these keys to access in mapStateToProps.
From the redux docs:
The state produced by combineReducers() namespaces the states of each
reducer under their keys as passed to combineReducers()
You can control state key names by using different keys for the
reducers in the passed object. For example, you may call
combineReducers({ todos: myTodosReducer, counter: myCounterReducer })
for the state shape to be { todos, counter }.
So your mapStateToProps must be like:
const mapStateToProps = state => {
console.log(state);
return {
inputVal: state.InputReducer.inputVal
}
};
A minimal working code sandbox:
https://codesandbox.io/s/cold-meadow-pxtu3

Redux: What is the best way to toggle a boolean value in a normalized state tree?

I'm currently developing an app with React Native. The state of the app is quite complex, but managable due to Redux and Normalizr. I now have to implement a functionality for the user to filter items.
In order for the user to filter items, I enriched the server response in the Normalizr schema:
export const subCategorySchema = new schema.Entity(
"subCategories",
{},
{
idAttribute: "uuid",
processStrategy: entity => {
const newEntity = Object.assign({}, { name: entity.name, uuid: entity.uuid, chosen: false });
return newEntity;
}
}
);
The corresponding reducer now looks like this:
const initialState = {};
const subCategoriesReducer = (state = initialState, action) => {
if (action.payload && action.payload.entities) {
return {
...state,
...action.payload.entities.subCategories
};
} else {
return state;
}
};
These the subcategories now get displayed in the UI using this SwitchListItem component, which gets it's items through a selector:
import React, { Component } from "react";
import { Switch, Text, View } from "react-native";
import PropTypes from "prop-types";
import styles, { onColor } from "./styles";
export default class SwitchListItem extends Component {
static propTypes = {
item: PropTypes.object
};
render() {
const { name, chosen } = this.props.item;
return (
<View style={styles.container}>
<Text style={styles.switchListText}>{name}</Text>
<Switch style={styles.switch} value={chosen} onTintColor={onColor} />
</View>
);
}
}
I'm now about to implement the <Switch /> component's onValueChange() function, which is where my question arose:
What is the best way to toggle a boolean value in a normalized state tree?
I came up with two solutions, which I will describe below. Please let me know if you think any one of these is good. If not I would love to get advice on what I could do better :)
Solution 1: Extending the reducer:
My first solution for the problem was to extend the reducer to listen to TOGGLE_ITEM actions. This would look something like this:
const subCategoriesReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_ITEM:
if (action.payload.item.uuid in state) return { ...state, ...action.payload.item };
}
if (action.payload && action.payload.entities) {
return {
...state,
...action.payload.entities.subCategories
};
} else {
return state;
}
};
This is my preferred solution as it does not need a lot of code.
Solution 2: Enriching the selector that passes the items to the SwitchList:
The other solution would be to enrich the objects while being passed to the list using a selector with it's key for the state. Then I could create an action that uses this key to update the state like this:
const toggleItem = (item, stateKey) => ({
type: TOGGLE_ITEM,
payload: {entities: { [stateKey]: item } }
})
I would love to read an answer, preferably opinionated, if you have a lot of experience with Redux. Also, if you think my way of enriching the data in the normalizr is bad and you can come up with a better way, please let me know! Thank you very much for any advice!
I did it in a completely different way.
I created an array that holds the uuids of the toggled items. Therefore I only need to look, whether the item is in the toggled array.
Just like this:
const initialState = {};
export const byId = (state = initialState, action) => {
if (action.payload && action.payload.entities && action.payload.entities.itemClassifications) {
return {
...state,
...action.payload.entities.itemClassifications
};
} else {
return state;
}
};
export const chosen = (state = [], action) => {
if (action.type === TOGGLE_ITEM && action.meta === ITEM_CLASSIFICATION) {
if (state.includes(action.payload.uuid)) {
return state.filter(uuid => uuid !== action.payload.uuid);
} else {
return [...state, action.payload.uuid];
}
} else {
return state;
}
};
const itemClassificationsReducer = combineReducers({
byId,
chosen
});
export default itemClassificationsReducer;
export const getAllItemClassificationsSelector = state =>
Object.values(state.itemClassifications.byId);
export const getAllItemClassificationsNormalizedSelector = state => state.itemClassifications.byId;
export const getChosenItemClassificationsSelector = state => state.itemClassifications.chosen;
export const enrichAllItemClassificationsSelector = createSelector(
getAllItemClassificationsSelector,
itemClassifications =>
itemClassifications.map(val => ({ ...val, stateKey: ITEM_CLASSIFICATION }))
);
export const getItemClassificationsFilterActiveSelector = createSelector(
getChosenItemClassificationsSelector,
itemClassifications => itemClassifications.length > 0
);

State does not change in my reducer when action is dispatched

I am not able to retrieve the state in the reducer
MyComponent looks like this
const MyComponent = ({name, features, onClick}) => {
return (
<div>
Hello! {name}
<Button onClick={() => { onClick(features); }}> Weight</Button>
</div>
);
const mapDispatchToProps = (dispatch: any) => {
return {
onClick: (features) => {
dispatch(weightSort(features));
}
};
};
const mapStateToProps = (state: any, ownProps: any) => {
console.log(state); //Displays the state
return {
name: "John Doe",
features: ownProps.features,
};
};
export const FeatureBlock = connect(mapStateToProps, mapDispatchToProps)(MyComponent);
My actions and reducers looks like below:
// Action Creator
export const weightSort = (features) => {
console.log("inside the weight sort action creator!!!");
return {
type: "SET_WEIGHT_FILTER",
filter: "DESC",
features,
};
};
// Reducer
export const weightFilter = (state = [], action) => {
switch (action.type) {
case "SET_WEIGHT_FILTER":
console.log(state); // Gives me empty state
console.log("++inside weight filter+++++", action); //Displays action
return state;
default:
return state;
}
};
export const FeatureBlock = connect(
mapStateToProps,
mapDispatchToProps,
)(MyComponent);
What am I missing here? Any help will be appreciated!
In your reducer, when you console.log(state), it is correct in returning an empty array because you haven't done anything to modify it.
// Reducer
export const weightFilter = (state = [1,2,3], action) => {
switch (action.type) {
case "SET_WEIGHT_FILTER":
console.log(state); // This will show [1,2,3] because [1,2,3] is the initial state.
console.log("++inside weight filter+++++", action); //Displays action
return state;
default:
return state;
}
};
My guess is that you want something like this for your reducer:
// Action Creator
export const weightSort = (name, features) => {
console.log("inside the weight sort action creator!!!");
return {
type: "SET_WEIGHT_FILTER",
name,
features,
};
};
// Reducer
export const weightFilter = (
state = {
name: '',
features: [],
},
action
) => {
switch (action.type) {
case "SET_WEIGHT_FILTER":
return {...state, name: action.name, features: action.features}
default:
return state;
}
};
and then in your mapStateToProps you would map out the attributes like so:
const mapStateToProps = (state: any, ownProps: any) => {
console.log(state); //Displays the state
return {
name: state.weightFilter.name,
features: state.weightFilter.features,
};
};
and your button would have a name prop passed into the function like so:
<Button onClick={() => { onClick(name, features); }}> Weight</Button>
If you would like to sort your data, you can do so either in the reducer or inside the container. I prefer to do it in the container and like to use the lodash sortBy function. It works like this:
import { sortBy } from 'lodash' //be sure to npm install lodash if you use this utility
...
...
function mapStateToProps(state) {
return {
name: state.weightFilter.name,
features: sortBy(features, ['nameOfPropertyToSortBy'])
};
}
Here is the lodash documentation on sortBy: https://lodash.com/docs/4.17.4#sortBy
Hope that helps!

Resources