'why we use arrayed property instead of using it directly [duplicate]
My question is why we use [action.fieldName]: action.payload?
Why we couldn't use action.fieldName: action.payload?
import './App.css';
import React,{useReducer} from 'react';
const initialState = {
username: "",
password: "",
isLoggedIn: false,
error: false,
};
function reducer(state, action){
switch(action.type){
case "FIELD_CHANGE":
return {
...state,
[action.fieldName]: action.payload,
}
default:
return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
const { username, password, isLoggedIn, error } = state;
console.log(state);
return (
<div className="App">
<label htmlFor="username">Username: </label>
<input type="text" name="username" onChange={(e)=> dispatch({type:"FIELD_CHANGE",fieldName:"username",payload:e.target.value})}/>
<label htmlFor="password">Password: </label>
<input type="text" name="password" onChange={(e)=> dispatch({type:"FIELD_CHANGE",fieldName:"password",payload:e.target.value})}/>
<div>
{username}
</div>
</div>
);
}
export default App;
I understand that there will be more than one fieldName but once we specify them individually using ...state it should automatically add since it will be different input name (username & password).
Solution 1:[1]
why we couldn't use action.fieldName: action.payload
You cannot use action.fieldName as key as it will throw error. You can use 'action.fieldName' but the key name will not be the value of action.fieldName . In order to use the value of action.fieldName as object key name you need to use []
[] is called Computed Property Names, its implemented using bracket notation( square brackets) []
Solution 2:[2]
For example, if you write the code :
const myFirstObject={property1:"cool",property2:"bad"}
const testObject={[myFirstObject.property1]:myFirstObject.property2}
console.log(testObject);
in your console, you have:
{cool: "bad"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kiranvj |
| Solution 2 | Fred |
