-1

I'm working in React Redux, and I am trying to return a value from a simple array in my reducer. Here are my short files:

App.js

let arr = [{"name": "Matthew"}];

function App() {
    const dispatch = useDispatch();
    dispatch(action1(arr));

    return(
        <div>
            <List />
        </div>
    );
}

List.js

function List(){
    const val = useSelector(getVals);

    return(
        <div>
            {val}
        </div>
    )
}

Actions.js

export function action1(arr){
    return { type: ADD_STORE, arr};
}

Reducer.js

function AddToStore(state = [], action){
    switch(action.type){
        case ADD_STORE:
            return [...action.name, ...state];
    }
}

export default AddToStore;

This is giving me the error "object is not iterable." Why? Instead of an array, if I just pass a string, for example "Matthew", I can print it out fine by returning [...action, ...state].

user545642
  • 91
  • 1
  • 14

2 Answers2

0

It's not working because in your store you're trying to return an array instead of an object. More about redux principals here: https://redux.js.org/introduction/three-principles#single-source-of-truth

App.js

let objNames = {names: [{"name": "Matthew"}]};

function App() {
    const dispatch = useDispatch();
    dispatch(action1(arr));

    return(
        <div>
            <List />
        </div>
    );
}

Reducer.js

function AddToStore(state, action){
    switch(action.type){
        case ADD_STORE:
            return {...action.names, ...state};
    }
}

export default AddToStore;

And changed the action.js to pass in objNames instead of arr.

Sidah Merzouk
  • 584
  • 5
  • 18
0

I fixed the issue by change curly braces by [].

const initialState = {
  clients: [],
  loading: false,
};
export default function clientReducer(state = initialState, action) {
switch (action.type) {

    case ADD_CLIENT:
          return [action.clients, state];
 default:
      return state;
}
}