Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why we use arrayed property instead of using it directly

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading