Making controlled inputs with Redux Toolkit

Viewed 23

I've been trying to find a solution to how to make a single onChange listener for different inputs and then pass all the info to the single RTK state.

So, basically, the listener has to collect information from every input and then pass it to the correspondending object key which is in the array.

My slice looks like this:

import { createSlice } from '@reduxjs/toolkit';
import uniqid from 'uniqid';

// State

const initialState = [
  {
    id: uniqid(),
    course: '',
    university: '',
    fromEd: '',
    toEd: '',
    descriptionEd: '',
  },
];

const educationSlice = createSlice({
  name: 'education',
  initialState,
  reducers: {
    addEducation: (state) => {
      state.push({
        id: uniqid(),
        course: '',
        university: '',
        fromEd: '',
        toEd: '',
        descriptionEd: '',
      });
    },
    removeEducation: (state, action) => {
      state.splice(action.payload, 1);
    },
    updateEducation: (state, action) => {
      ------> ??? <-----
    },
  },
});

export default educationSlice.reducer;
export const { addEducation, removeEducation, updateEducation } =
  educationSlice.actions;

And my components looks like this:

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateEducation } from '../../features/educationSlice';

function Education() {
  const education = useSelector((state) => state.education);
  const dispatch = useDispatch();

  const handleEducationChange = (???) =>
    dispatch(updateEducation(???));

  return education.map((el, index) => (
    <span key={index}>
      <h3 className='form-header'>Education</h3>
      <input
        onChange={handleEducationChange}
        value={el.course}
        className='form-input'
        type='text'
        name='course'
        placeholder='Course / Program'
      />
      <input
        onChange={handleEducationChange}
        value={el.university}
        className='form-input'
        type='text'
        name='university'
        placeholder='University'
      />
      <input
        onChange={handleEducationChange}
        value={el.fromEd}
        className='form-input'
        type='text'
        name='fromEd'
        placeholder='Start Date'
      />
      <input
        onChange={handleEducationChange}
        value={el.toEd}
        className='form-input'
        type='text'
        name='toEd'
        placeholder='End Date'
      />
      <input
        onChange={handleEducationChange}
        value={el.descriptionEd}
        className='form-input'
        type='text'
        name='descriptionEd'
        placeholder='Description'
      />
      ...    
0 Answers
Related