Skip to content
Advertisement

How to pass in a string as a single value and not a split value

I have a function called onClick of a div that calls a dispatch function, and passes in the target value into it (i.e e.target.value). The value being passed in, is being stored in an array.

However, I noticed something weird going on. In the array the value is being passed into, the first value is stored wrongly.

For instance if I pass in 'hello', in the array, it is stored as ['h','e','l','l','o']. And this only happens with the first value that is passed in, the rest are stored properly.

This is my function, the one called onClick;

const handleSelectedFilters = (e: any) => {
  dispatch(
    actions.storeData({
      name: data.name,
      values: e.target.value,
    }),
  );
}

And this is the action in my reducer file;

export interface DataState {
  name: string,
  values: Array<string>,
}

export interface FilterState {
  storedData: DataState[];
}

applyData: (
      state,
      action: PayloadAction<DataState>,
    ) => {
        state.storedData.push({
          name: action.payload.name,
          values: [...action.payload.values],
        });
    },

Please any help will be appreciated as I am really stuck. What do I need to do differently?

Advertisement

Answer

You’re storing your values as values: [...action.payload.values]

If you do:

var text: String = "hello":
console.log([...text]);

You will see how the spread operator placed inside the array will split your string into an array.

Solution

Just save it as values: action.payload.values

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement