Home > other >  How to change the state of a component when another changes?
How to change the state of a component when another changes?

Time:09-10

How can I change the state of a component when another changes?

When the state of a select changes AssetType, the value of the select AssetTypeCategory must be set to 0

  const handleAssetType = (e)=>{
    setAssetType(e.target.value),
    setAssetTypeCategory(0),
  }


  <div>
    <label htmlFor="AssetType>Asset Type:</label>
    {Array.isArray(state.AssetType) ? (
      <select
        name="AssetType"
        id="AssetType"
        value={state}
        onChange={handleAssetType }
      >
        <option key="0" value="0">
          -- PICK A ITEM--
        </option>
        {state.AssetType.map((x) => (
          <option key={x.id} value={x.id}>
            {x.name}
          </option>
        ))}
      </select>
    ) : null}
  </div>

CodePudding user response:

Do you using class or functional component ? It looks like you using class component , u cant change class component's state this way , use setState and spread "..." operator.

CodePudding user response:

The code is wrong for two reasons.

1 - You dont need to use comma to separate functions. The code would be:

  const handleAssetType = (e)=>{
  
    setAssetType(e.target.value)
    setAssetTypeCategory(0)
  }

2 - If you do setAssetType(e.target.value) the value is a int, so AssetType is not an array, making a blank page.

CodePudding user response:

You should exec your handleAssetType function in this way.

const handleAssetType = (e)=>{
    setAssetType(e.target.value),
    setAssetTypeCategory(0),
  }

  <div>
    <label htmlFor="AssetType>Asset Type:</label>
    {Array.isArray(state.AssetType) ? (
      <select
        name="AssetType"
        id="AssetType"
        value={state}
        onChange={(e) => handleAssetType(e) }
      >
        <option key="0" value="0">
          -- PICK A ITEM--
        </option>
        {state.AssetType.map((x) => (
          <option key={x.id} value={x.id}>
                {x.name}
              </option>
            ))}
         </select>
      ) : null}
  </div>
  • Related