I am currently working on a project in React Native where I use react-redux.
Now I have the situation in which I would like to call the dispatch hook with a dynamic input. However it just do not work but I get no error message in the console.
Some remarks:
- the user Object contains the key value pairs I want to add to the state (e. g. name: John Doe)
- I tried multiple versions of asigning the function name to the dispatch hook but all failed
Can anyone tell me, what I am doing wrong?
My current Code:
import {
resetCompleteStoreState,
setAdressCity,
setAdressZipcode,
setEmail,
setName,
setPhone,
} from "../../../app/redux/features/auth/userSlice";
... more Code ...
var functions = new Map();
[setAdressCity, setAdressZipcode, setEmail, setName, setPhone].forEach(
(fn) => {
functions.set("" fn, fn);
}
);
for (let [key, value] of Object.entries(response.data.data.user)) {
if (key.includes("_")) {
var i,
frags = key.split("_");
for (i = 0; i < frags.length; i ) {
frags[i] = frags[i].charAt(0).toUpperCase() frags[i].slice(1);
}
key = frags.join("");
} else {
key = key.charAt(0).toUpperCase() key.slice(1);
}
if (key != "Id") {
stateMethod = functions.get("user/set" key);
dispatch(stateMethod(value));
}
}
CodePudding user response:
you can't call a function from a string unless you store them in some object that do the translation
like this
import {
resetCompleteStoreState,
setAdressCity,
setAdressZipcode,
setEmail,
setName,
setPhone,
} from "../../../app/redux/features/auth/userSlice";
... more Code ...
const functions = new Map()
[ setAdressCity,
setAdressZipcode,
setEmail,
setName,
setPhone].forEach(fn => {
functions.set(fn.name, fn)
})
for (let [key, value] of Object.entries(response.data.data.user)) {
if (key.includes("_")) {
var i,
frags = key.split("_");
for (i = 0; i < frags.length; i ) {
frags[i] = frags[i].charAt(0).toUpperCase() frags[i].slice(1);
}
key = frags.join("");
} else {
key = key.charAt(0).toUpperCase() key.slice(1);
}
if (key != "Id") {
// dispatch("user/set" `${key}` `(${value})`);
// dispatch(`set${key}`(`${value}`));
test = functions["set" key];
console.log(test);
dispatch(test(`${value}`));
}
}