Redux Action is Dispatched but state not updating accordingly

Viewed 635

When i click the delete button the action(removeBus) is dispatched and the correct payload value is sent however the store is not updating here is my busSlice file

import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

here is where i created and export the store

import { configureStore } from "@reduxjs/toolkit";
import busReducer from "../features/busSlice";
export const store = configureStore({
  reducer: {
    busses: busReducer
  }
});

the component that uses the state is created in the following code and App is wrapped inside a redux provider Component and the above store is provided as a props in index.js

import "./styles.css";
import { useSelector, useDispatch } from "react-redux";
import { removeBus } from "./features/busSlice";
export default function App() {
  const dispatch = useDispatch();
  const busses = useSelector((state) => state.busses);
  const handleRemove = (id) => {
    dispatch(removeBus(id));
  };

  return (
    <div className="App">
      {busses.map((bus) => (
        <ul>
          <li key={bus.id}>
            <p>{bus.description}</p>
            <button onClick={() => handleRemove(bus.id)}>delete</button>
          </li>
        </ul>
      ))}
    </div>
  );
}

using redux dev tools i can see an action busses\removeBus is dispatched with the appropriate payload value but nothing is happening to the state.

3 Answers

You can change:

removeBus: (state, action) => {
      state.filter((bus) => bus.id != action.payload);
      console.log(action.payload);
    }

can be the data types of bus.id and action.payload are different.

you are not updating state correctly you need to say change my state to filtered state

like this

removeBus(state, action){
      state = state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
}

I also had this issue.

I my case, code looked like this:

const someSlice = createSlice({
  name: 'test',
  initialState: null, 
  reducers: {
  addData(state, action) {
     state = action.payload
   }
 } 
});

This did not work

const someSlice = createSlice({
  name: 'test',
  initialState: null, 
  reducers: {
  addData(state, action) {
     state = action.payload;
     return state;
   }
 } 
});

this worked.

But this is very strange, should not work this way.

Related