1

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).

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
reactify91
  • 13
  • 2

2 Answers2

0

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) []

kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • @reactify91 I have also provided a similar solution which might be useful for you - https://stackoverflow.com/a/11508530/1188322 – kiranvj Apr 06 '22 at 06:38
0

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"}
Fred
  • 278
  • 2
  • 6