'Problem at reading an array from redux store, the array is concatenated
I came to ask for help in a Redux project with arrays. I have two variables, a string and an array and I'm only able to use the string variable. For my problem I'll simplify things in an example, but in my real array there are a lot more elements.
let x = "test1";
let y = ["test2","test3"];
And what happens? During the path of the variables to the end, if I give a console log, it's OK. Even the array is "still" an array. But when pulling it from the store, it comes concatenated
// teste2teste3
so like... it's no longer an array. If I give a console log, it's still shown as array. Now if I give an index to the variable (var[0] or var[1]), it gives undefined because these index's don't exist. So I probably have to do something I didn't care about. But just reporting it again, the string variable is fine, so at least the Redux structure is right, I imagine it must be something in the reducer.
Follow the data:
1st Dispatch as array itself is right ["teste2","teste3"] because I can give console log in the reducer and at least it gets there right.
DISPATCH
const dispatch = useDispatch();
setdispatch(["test2","test3"]);
const setdispatch = (args) => {dispatch(actiontest(args))};
2nd Action I think it's right here too
ACTIONS
export const actiontest= (args) => {
return {
type: "TEST",
payload:{test:args}
};
};
3rd Reducer I think the error must be here
REDUCER
const testReducer = (state = "", action) => {
switch(action.type) {
case "TEST":
return {
...state,
testpayload: action.payload.test,
};
default:
return state;
}
4th Load from Store
USELECTOR
const testReducer = useSelector((state) => state.test);
console.log(testReducer.testpayload);
//Array(2)
0: "Test2"
1: "Test3"
So far it's ok. Now making a jsx {testeReducer.testepayload}
//Test2Test3
And testReducer.testepayload[0] gives undefined, because it looks like it is no longer an array. And the other variable test1 is fine here. I tried turning the payload into an array, even though it was already an array, just to test it out.
testpayload: [action.payload.test],
Array(1)
0: Array(2)
0: "test2"
1: "test3"
Anyway, the problem doesn't change anything.
So until I solved the problem, I had to stick with multiple variables, one for each value, what a shame. Anyone who can help me out there, thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
