Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react redux updating state on input change

Tags:

reactjs

redux

I'm making a page using react redux which has 14 input tags.

I have 14 different names in state for each of the input tag.

What do I do to update the state whenever any of the input changes?

Do I need to write actions and reducers for every input tag?

like image 841
sachsure Avatar asked Nov 26 '25 05:11

sachsure


2 Answers

For sure you have to refactor your app to have a single action like:

{ type: 'UPDATE', field: '<name of your field>', value: <value here> }

And then in your reducer:

case 'UDPATE':
  const { field, value } = action.payload;

  return { ...state, { [field]: value }};
like image 188
Krasimir Avatar answered Dec 02 '25 02:12

Krasimir


If you are updating properties in one reducer you can do something like this:

Dispatch the updated value in an object and then merge it with the previous state in the reducer.

dispatch({
  type: 'UPDATE_FIELD',
  data: { banana: 'yellow' },
});

In your reducer:

case 'UPDATE_FIELD':
  return {
    ...state,
    ...data,
  };
like image 31
Max Avatar answered Dec 02 '25 00:12

Max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!