How to use a reducer for multiple actions in Redux? - javascript

I'm new using Redux, and I'm trying to integrate React with Redux. What I want is to put all my actions in one reducer. Actually my reducer looks like this:
import {GET_ALL_CONNECTIONS, DELETE_CONNECTION, POST_CONNECTION} from '../actions';
const initialState = {
}
export default (state = initialState, { type, payload }) => {
switch (type) {
case GET_ALL_CONNECTIONS:
return payload
case POST_CONNECTION:
return {...state, ...payload}
case DELETE_CONNECTION:
return {...state, ...payload}
default:
return state
}
}
The problem is when I call the action corresponding to the GET_ALL_CONNECTIONS type:
export const getAllConnections = () => {
return async (dispatch) =>{
const response = await Conexiones.get('/db/myConnections');
dispatch({type: GET_ALL_CONNECTIONS, payload: response.data});
}
}
When I call this function in a React component is supposed to get multiple connections from an API, and save the array of object resultant of the API call in the state.
The problem is when I want to save the connections array in the state, to later map that state and generate options with each one of the connection inside a select element. When I render the component it throws me the next error:
TypeError: this.props.conexiones.map is not a function
The file where I combine all reducers looks like this:
import {combineReducers} from 'redux';
import {reducer as formReducer } from 'redux-form';
import postUser from './postUser';
import postConnection from './postConnection';
import getAllConnections from './getAllConnections';
import ConnectionsReducer from './ConnectionsReducer';
export default combineReducers({
newUser: postUser,
form: formReducer,
conexiones: ConnectionsReducer
});
And the component where I do the call looks like this:
import React, { Component } from 'react';
import { Grid, Container, Select, Button, withStyles, FormControl, InputLabel, MenuItem } from '#material-ui/core';
import {connect} from 'react-redux';
import {reduxForm, Field} from 'redux-form';
import {deleteConnection, getAllConnections} from '../actions';
const styles = theme => ({
root: {
display: 'flex',
flexWrap: 'wrap',
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
});
class BorrarConexion extends Component {
componentDidMount() {
this.props.getAllConnections();
}
handleSubmit = ({conexionId}) => {
this.props.deleteConnection(conexionId);
}
renderConexiones = () => {
return this.props.conexiones.map(conexion =>{
return (<MenuItem key={conexion.id} value={conexion.id}>{conexion.connectionUrl}</MenuItem>);
});
}
renderSelectField = ({input,label,meta: { touched, error },children,...custom}) =>{
return (
<FormControl>
<InputLabel>Seleccione la URL que desea eliminar</InputLabel>
<Select {...input} {...custom}>
{this.renderConexiones()}
</Select>
</FormControl>
)
}
render() {
return (
<Container>
<Grid container direction="column">
<Field name="conexionId" component={this.renderSelectField} label="Favorite Color"/>
<Button onClick={this.props.handleSubmit(this.handleSubmit)}>Eliminar</Button>
</Grid>
</Container>
);
}
}
const mapStateToProps = (state) => {
return {conexiones: state.conexiones}
}
const BorraConexionEstilizado = withStyles(styles)(BorrarConexion);
const formWrapped = reduxForm({form: 'delete_connection'})(BorraConexionEstilizado);
export default connect(mapStateToProps, {getAllConnections, deleteConnection})(formWrapped);
When I do this with a separate reducer called getAllConnections and replace the conexiones: ConnectionsReducers with conexiones: getAllConnections it works. The getAllConnections reducer looks like this:
export default (state = [], { type, payload }) => {
switch (type) {
case 'GET_ALL_CONNECTIONS':
return payload
default:
return state
}
}
I want to know how to do this work with one reducer receiving all my actions instead of a individual reducer for each action.

This issue is related to the fact that you are likely returning different structures from your reducer. It looks like the reducer is meant to handle objects as state but for this one case you return an array. Objects do not have a map function. You need to determine the structure of your state for this reducer and stick with it, you cannot change from array to object and back again, that is undeterministic behavior that redux is not built for.
I do not know the implementation details of your APIs but this is the main area in need of updating
const initialState = []
export default (state = initialState, { type, payload }) => {
switch (type) {
case GET_ALL_CONNECTIONS:
return payload //hoping that your api gave an array here
case POST_CONNECTION:
//return {...state, ...payload} //this is clearly returning an object
return [...state, payload] //now it returns an array with a new item
case DELETE_CONNECTION:
//return {...state, ...payload} //this is clearly returning an object
return state.filter(item => item.id !== payload.id) //now it returns a filtered array
default:
return state
}
}
The following code should recieve states as arrays and return updated states as arrays.

You have to set initial state... right now, your state is an empty object

I solved this issue by surrounding the conexion:state.conexion in the mapStateToProps method with Object.values() like this:
conexion: Object.values(state.conexion)

Related

no data is passed into state when using useContext/useReducer together with useQuery

export const itemReducer = (state, action) => {
switch (action.type) {
default:
return state
}
}
import React, { useState, useReducer, createContext, useContext } from 'react'
import { useQuery } from '#apollo/client'
import { CURRENT_MONTH_BY_USER } from '../graphql/queries'
import { itemReducer } from '../reducers/ItemReducer'
const Items = createContext()
export const ItemProvider = ({ children }) => {
let items = []
const [state, dispatch] = useReducer(itemReducer, { items: items })
const result = useQuery(CURRENT_MONTH_BY_USER)
if (result.data && result.data.getCurrentMonthByUser) {
items = [...result.data.getCurrentMonthByUser]
}
return <Items.Provider value={{ state, dispatch }}>{children}</Items.Provider>
}
export const ItemsState = () => {
return useContext(Items)
}
export default ItemProvider
let items gets correct data from the useQuery, however nothing is passed into the state, therefore I am unable to transfer data into another components from the context. What am I doing wrong here?
When debugging both items and state they're initially empty because of the loading however then only the items receives correct data and state remains as empty array.
If i put static data into let items it works just fine, so maybe there can be something wrong with my useQuery as well?
It's easy to see your problem if you look at where items is used. That's only as the initial state to your useReducer call - but items is only set to a non-empty value after this. That has absolutely no effect on the component, because items is not used later in your component function, and the initial state is only ever set once, on the first render.
To solve this you need to embrace your use of a reducer, adding a new action type to set this initial data, and then dispatching that when you have the data. So add something like this to your reducer:
export const itemReducer = (state, action) => {
switch (action.type) {
case SET_INITIAL_DATA: // only a suggestion for the name, and obviously you need to define this as a constant
return { ...state, items: action.items };
/* other actions here */
default:
return state
}
}
and then rewrite your component like this:
export const ItemProvider = ({ children }) => {
const [state, dispatch] = useReducer(itemReducer, { items: [] })
const result = useQuery(CURRENT_MONTH_BY_USER)
if (result.data && result.data.getCurrentMonthByUser) {
dispatch({ type: SET_INITIAL_DATA, items: result.data.getCurrentMonthByUser });
}
return <Items.Provider value={{ state, dispatch }}>{children}</Items.Provider>
}
Also, while this is unrelated to your question, I will note that your ItemsState export appears to be a custom hook (it can't be anything else since it isn't a component but uses a hook) - that is perfectly fine but there is a very strong convention in React that all custom hooks have names of the form useXXX, which I strongly suggest you should follow. So you could rename this something like useItemsState (I would prefer useItemsContext to make clear it's just a useContext hook specialised to your specific context).

React UI doesn't update on redux store change

I have a redux State HOC to manage the connection
I Have a problem when I add a new post to the store
import React, { useEffect } from "react";
import { connect } from "react-redux";
export default function withState(WrappedComponent) {
function mapStateToProps(reduxState) {
let state = {};
for(let t of Object.entries(reduxState)) {
state = {...state, ...t[1]}
}
return {
...state,
};
}
return connect(
mapStateToProps,
null
)(function (props) {
useEffect(() => {}, [props.posts, props.comments]) /*tried this but didn't work*/
return (
<React.Fragment>
<WrappedComponent {...props} />
</React.Fragment>
);
});
}
I am trying to make the program render the response from my back-end without me reloading the page manually
I tried using the useEffect
and I saw through the dev tools that the state change correctly
my reducer
import { GET_ALL_POSTS, CREATE_NEW_POST } from "../actions"
const initialState = {
posts: []
}
export default function postReducer(state = initialState, action) {
let newState = {...state}
switch(action.type){
case GET_ALL_POSTS:
return {
...newState,
posts: [...action.posts],
}
case CREATE_NEW_POST:
const posts = [...newState.posts, action.post]
return {
...newState,
posts
}
default:
return {
...newState,
}
}
}
I also read that react changes doesn't respond to shallow copies so I changed the whole array in the post reduces when I add a new post
Your withState HOC is very strange. I'm not sure why you don't just use connect directly (or use hooks). But try this:
export function withState(WrappedComponent) {
return connect(
(state) => ({
posts: state.postsReducer.posts,
comments: state.commentsReducer.comments
}),
null
)(WrappedComponent);
}

How to I convert my props data into an array in my React with Redux project?

In my solution which is an ASP.NET Core project with React, Redux, and Kendo React Components I need to return my props as an array. I'm using the Kendo Dropdown widget as below.
<DropDownList data={this.props.vesseltypes} />
However I receive the error of :
Failed prop type: Invalid prop data of type object supplied to
DropDownList, expected array.
So, I checked my returned data from the props.vesseltypes which is an array of as opposed to a flat array.
Here is my code for how this data is returned:
components/vessels/WidgetData.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { actionCreators } from '../../store/Types';
import { DropDownList } from '#progress/kendo-react-dropdowns';
class WidgetData extends Component {
componentWillMount() {
this.props.requestTypes();
}
render() {
console.log(this.props.vesseltypes)
return (
<div>
<DropDownList data={this.props.vesseltypes} />
</div>
);
}
}
export default connect(
vesseltypes => vesseltypes,
dispatch => bindActionCreators(actionCreators, dispatch)
)(WidgetData);
components/store/Types.js
const requestVesselTypes = 'REQUEST_TYPES';
const receiveVesselTypes = 'RECEIVE_TYPES';
const initialState = {
vesseltypes: [],
isLoading: false
};
export const actionCreators = {
requestTypes: () => async (dispatch) => {
dispatch({ type: requestVesselTypes });
const url = 'api/KendoData/GetVesselTypes';
const response = await fetch(url);
const alltypes = await response.json();
dispatch({ type: receiveVesselTypes, alltypes });
}
}
export const reducer = (state, action) => {
state = state || initialState;
if (action.type === requestVesselTypes) {
return {
...state,
isLoading: true
};
}
if (action.type === receiveVesselTypes) {
alltypes = action.alltypes;
return {
...state,
vesseltypes: action.alltypes,
isLoading: false
}
}
return state;
};
And finally, the reducer is defined in the store
components/store/configureStore.js
const reducers = {
vesseltypes: Types.reducer
};
Controllers/KendoDataController.cs
[HttpGet]
public JsonResult GetVesselTypes()
{
var types = _vesselTypeService.GetVesselTypes();
return Json(types);
}
So, the dropdown widget expects an array, what I return via the store is an array of objects. As such, this can't be used by the dropdown because it's not what it is expecting. My question is, how do I return this as a single array or flat array?
First deconstruct the part that you want to map to a property from your state:
export default connect(
({vesseltypes}) => ({vesseltypes}),
dispatch => bindActionCreators(actionCreators, dispatch)
)(WidgetData);
Then you could just map vesselTypes to an array of strings, since that's what Kendo DropdownList seems to expect:
<div>
<DropDownList data={this.props.vesseltypes.map((vessel) => vessel.TypeName)} />
</div>
Which should result in what you wanted to achieve.
Alternatively you could look into how to implement a HOC to map your objects to values, it's specified in the Kendo docs, or you can checkout the Stackblitz project they've prepared.
It looks like you forgot to extract vesselTypes from the response here
const alltypes = await response.json();
and your console.log shows that, it contains whole response not just vesselTypes array.
EDIT: On top of that your connect seems wrong, you just pass whole state as a prop not extracting the part you need.
I assume you need an array of strings where the value is in key TypeName.
First of all, I would suggest renaming your variables, if there isn't any back-end restriction like how it's returned via fetch.
For example, these:
alltypes => allTypes
vesseltypes => vesselTypes
Regarding the issue, you just need to do a quick transform before passing data into component. Not sure how the drop down component uses the original input data but I would reduce the array into separate variable to create it only once.
Then pass the variable vesselTypeList into component DropDownList.
Last thing is where to do this transform, when result has been retrieved and Redux updates your props via mapStateToProps first argument of connect function.
const getTypeList = (vesseltypes) => {
return vesseltypes.reduce((result, item) => {
result.push(item.TypeName);
return result;
}, []);
}
const mapStateToProps = ({ vesseltypes }) => { vesseltypes: getTypeList(vesseltypes) };
export default connect(
mapStateToProps,
dispatch => bindActionCreators(actionCreators, dispatch)
)(WidgetData);

React component not updating on redux state update

I am using react, redux and redux-saga for my project. While fetching a list of users using Redux-saga, I can see that my redux store is getting updated (I can see it from the redux dev tool), But in the component , props are not changing.
I am using a button to get the list of users. And the users are showing up in that component only.
App.js
import React, { Component } from 'react';
import { connect } from "react-redux";
import './App.css';
import { fetchUsers } from "./actions";
import { Row, Col, ListGroup, ListGroupItem } from "reactstrap";
class App extends Component {
// eslint-disable-next-line no-useless-constructor
constructor(props){
super(props);
}
render() {
console.log("in render func");
console.log(this.props);
return (
<div className="App">
<h2>Redux Saga App</h2>
<Row>
<Col sm={6}>
{this.props.userList?this.props.userList.map((user)=>(
user.first_name + user.last_name
)) : ''}
</Col>
</Row>
<button onClick={this.props.getUserList}>Click to get the users</button>
</div>
);
}
}
const mapStateToProps = (state)=>{
console.log("in map statetpprop");
//console.log(state.userList);
return {userList:state.userList}
}
const mapDispatchToProps = (dispatch)=>{
return {getUserList :() => {dispatch(fetchUsers())}}
}
App = connect(mapStateToProps,mapDispatchToProps)(App);
export default App;
action.js
export function fetchUsers(){
return {
type:'FETCH_USERS',
}
}
reducer.js
const initialState = {
userList:[]
}
export function userReducer(state=initialState,action){
switch(action.type){
case 'ADD_USER':
return Object.assign(state,{
user:action.data
})
case 'SET_USERS':
return Object.assign(state, {userList : action.data});
default:
return state;
}
}
saga.js
import {call, put , takeEvery , takeLatest } from 'redux-saga/effects';
import axios from 'axios';
import { setUsers } from "./actions";
export function fetchUsersFunc(userId){
return axios.get('https://reqres.in/api/users');
}
function* fetchUsers(action){
const users = yield call(fetchUsersFunc);
console.log("in fetch users");
if(users.data.data){
const userList = users.data.data;
console.log(userList);
console.log(userList[0].first_name)
yield put(setUsers(userList));
}
}
export function* rootSaga(){
yield [
takeLatest('FETCH_USERS',fetchUsers)
];
}
Thanks for the help!
If you use Object.assign and you want to make a new copy of the state, you need to make the target object to a new empty object instead of what you are currently doing (it mutates the state object, which makes the react unable to re-render). (You can see See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign for more information on Object.assign) For example:
// copy previous state and new updates to a new empty object
return Object.assign({}, state, {userList : action.data});
I would recommend using the spread operator instead of Object.assign though:
return {...state, userList : action.data}
If state is updated but UI is not, it means something went wrong with reducer.
Checkout reducer function carefully.
If you are using spread operator (...) in reducer function, make sure the updated data is mentioned explicitly after spread operator.
Example of working reducer function is as below:
const UvNumberReducer = (state=initialState, action: UVAction) => {
switch(action.type) {
case UV_NUMBER.LOAD:
return {
...state,
data: {
title: action.data.title,
subtitle: action.data.subtitle
}
}
default:
return state;
}
}

React, TypeError (this.props.data.map is not a function) on an Array obj

Thank you for stopping by to help. I am working with a react/redux app. One of the component is using a lifecyle method to retrieve data from an API. Once recieved, the data JSON data is held within an array. My initialState for the data coming back is an empty array.
When the component listening to the state change is mounted, the data is rendered on to the page, but then 2 seconds later I am getting a
Uncaught TypeError: jobs.map is not a function
Component making the API call using lifecyle method and listening for state change
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getJobs } from '../../actions';
import { Card, Grid, Image, Feed } from 'semantic-ui-react';
// import './home.css';
const renderJobs = jobs => jobs.map((job, i) => (
<Card.Group stackable key={i}>
<Card className="jobscard">
<Card.Content>
<Card.Header href={job.detailUrl} target="_blank">{job.jobTitle}</Card.Header>
<Card.Meta>{job.location}</Card.Meta>
<Card.Description>{job.company}</Card.Description>
</Card.Content>
</Card>
</Card.Group>
));
class GetJobs extends Component {
componentDidMount() {
this.props.getJobs();
}
render() {
const { jobs } = this.props;
return (
<div className="getjobs">
{renderJobs(jobs)}
</div>
);
}
}
export default connect(({ jobs }) => ({ jobs }), { getJobs })(GetJobs);
Action creator/action
export const getJobsRequest = () => fetch('https://shielded-brushlands-43810.herokuapp.com/jobs',
)
.then(res => res.json());
// action creator
export const getJobs = () => ({
type: 'GET_JOBS',
payload: getJobsRequest(),
});
Reducer
import initialState from './initialState';
export default function (jobs = initialState.jobs, action) {
switch (action.type) {
case 'GET_JOBS_PENDING':
return { ...jobs, isFetching: true };
case 'GET_JOBS_FULFILLED':
return action.payload;
case 'GET_JOBS_REJECTED':
return jobs;
default:
return jobs;
}
}
And intial state
export default {
userData: {},
jobs: [],
}
enter image description here
any thoughts on why this is happening?
You can put a simple check to ensure that your jobs is ready before you attempt rendering it.
{jobs.length && renderJobs(jobs)}

Categories