0

Not Sure why the value of state each time the onChange is running is equal to initial state value. This means that when I change the value of a component having this onChange attached, only it's value is set and rest all are unset as that's what is their initial value. The framework used is nextJS.

import { useState, ChangeEvent } from 'react';
import { IInitialState } from '../types';

const INITIAL_STATE: IInitialState = {
  companySize: '',
  salesChannel: '',
  brandWebsite: '',
  customersCatered: '',
  productCategories: [],
};

type FieldType = keyof IInitialState;

export function useMyCustomHook() {
  const [state, setState] = useState<IInitialState>(INITIAL_STATE);
  console.log('run');

  function onChange(
    selectedItem: string,
    field: FieldType,
    data?: Array<number>
  ) {
    const value = selectedItem;
    let newState: IInitialState;
    if (field !== 'productCategories') {
      console.log(state, { ...state });
      newState = { ...state, [field]: value };
    } else {
      if (!data) {
        console.log('here');
        return;
      }
      newState = { ...state, [field]: data };
    }
    console.log(field, selectedItem, newState);
    setState(newState);
  }

  function removeSelectedCategory(productId: number | string) {
    const newProductCategoriesList = state.productCategories.filter(
      item => item != productId
    );
    setState({ ...state, productCategories: newProductCategoriesList });
  }

  return {
    state,
    onChange,
    removeSelectedCategory,
  };
}
Abhishek Sharma
  • 617
  • 1
  • 9
  • 17
  • Wrap the `onChange` function in a [`useCallback`](https://reactjs.org/docs/hooks-reference.html#usecallback) with `state` in the dependencies array, so it picks up the updated value for the state whenever is changes. – juliomalves Feb 19 '22 at 17:04

0 Answers0