Home > other >  Eval() alternative for variable name in React JS
Eval() alternative for variable name in React JS

Time:10-11

I've been reading about how eval() can be harmful. I am getting into React and I would love to learn the best practices so that I don't keep building up bad habits. So, is there a better alternative for this?

Here's my code

const [paidValue, setPaidValue] = useState(props.expense.paid);
const [nameValue, setNameValue] = useState(props.expense.name);

const inputBlurHandler = (e) => {
        updateExpense(id, { [e.target.name]: eval(`${e.target.name}Value`) }); 
        setSuccGreen("updatedSucc"); }

and bunch of inputs with names

<input name={"name"} type={"text"} onBlur={inputValueBlur }... />
...

I was using a switch statement, depending on the input name, I use the corresponding value, but I was able to replace 8 lines of code with just one using the eval()

CodePudding user response:

I suppose you could just use a map (?)...

const [paidValue, setPaidValue] = useState(props.expense.paid);
const [nameValue, setNameValue] = useState(props.expense.name);

const map = { paidValue, nameValue };

const inputBlurHandler = (e) => {
        updateExpense(id, { [e.target.name]: map[e.target.name] }); 
        setSuccGreen("updatedSucc"); }

However, it will return undefined if you either forgot to include something in the map, or the name wasn't in the map, which may or may not be worse than erroring (since eval would).


You might want to consider using a state management library as well if this gets out of control. They do it a lot better than just a map (that is really just an object using shorthand property initializer).

CodePudding user response:

to me is seems that these should not be two separate states.

const [state, setState] = useState(props.expense);

const inputBlurHandler = (e) => {
    updateExpense(id, { [e.target.name]: state[e.target.name] }); 
    setSuccGreen("updatedSucc"); 
}
  • Related