Search code examples
reactjsrestreduxwebapireact-fullstack

react redux not displaying the correct data


i've taken a few courses on react and redux and so far the challenges are still piling up. i'm creating a simple app were at the time i need to just map the response from the api, but the state looks weird. the actions is returning the data, but is being displayed awkward. Please see the images attached. Does anyone know why the console.log of the data returns a number instead of an object or array name? also if you see the state from the redux dev tools, you can see that where an object name would be displayed, you see undefined instead. Please help. I've been at it for a couple of days and have been banging my head against the wall. enter image description here

enter image description here enter image description here enter image description here

reducer
import _ from 'lodash';

import { 
FETCH_CLIENT,
FETCH_CLIENTS,
ADD_CLIENTS_COMMENTS
} from "../actions/types";

export default (state = {}, action) => {
switch (action.type) {
case FETCH_CLIENT:
  return { ...state, ..._.mapKeys(action.payload, 'ClientUno') };
case FETCH_CLIENTS:
  return { ...state, [action.payload.ClientUno]: action.payload };
case ADD_CLIENTS_COMMENTS:
    return { ...state, [action.payload.ClientUno]: action.payload }; 
default:
  return state;
}
 };
 
combined reducer
import { combineReducers } from "redux";
import ClientsReducer from "./ClientsReducer";

export default combineReducers({
clients:ClientsReducer
});

action
const mapStateToProps = state => {
return{
    clients:Object.values(state.clients),
}
}

export default connect(mapStateToProps,{fetchAllClients})(Clients);

after removing .ClientUno. This my new state

enter image description here

post man response attachedenter image description here


Solution

  • It looks like your reducer logic is wrong:

    return { ...state, [action.payload.ClientUno]: action.payload }
    

    Per the screenshots, your action.payload is an array of items. The individual items do have a .ClientUno field inside them. But the array most definitely will not. So, action.payload.ClientUno is indeed undefined, and that's what you're using as a key.

    You'll need to rethink what you want to use as a key there. I don't know how you're actually trying to structure this slice state, so I can't provide a suggestion there.

    I will note that the Redux patterns you're using here are very outdated. "Modern Redux" with Redux Toolkit is much simpler and easier to use - there's no "ACTION_TYPES", switch statements, or object spreads. Please see our official Redux docs tutorials to learn how to use Redux Toolkit:

    https://redux.js.org/tutorials/index