Home > Net >  Sate does not change on dispatch React Native - Redux
Sate does not change on dispatch React Native - Redux

Time:10-05

I´m trying to fix this bug since one day and it won´t work.. I´m using dispatch but it never changes the state. The Slice should be right (it is really near to the online example from the redux-toolkit homepage )

This is my code:

App.tsx

export const StateDisplay = () => {
  const data = useAppSelector(selectErrors);
  const dispatch = useAppDispatch();
  function onPressMethod() {
    dispatch(
      errorActions.addNewOne({ type: "thisIsAType", value: "thisIsAValue" })
    );
  }

  return (
    <View>
      <Text>STATE :</Text>
      <Button title="add" onPress={onPressMethod}></Button>
      <FlatList
        data={data}
        renderItem={({ item }) => <Text>{item.value}</Text>}
      />

      <Text></Text>
    </View>
  );
};

Store:

export const store = configureStore({
    reducer: {
        errors: errorListSlice.reducer,
    },
});

Slice:

export interface dto {
    value: string;
    type: string;
}

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const selectErrors = (state: RootState) => state.errors;
const initialState: dto[] = [
    { value: "val1", type: "type1" },
    { value: "val1", type: "type1" },
];

export const errorListSlice = createSlice({
    name: "errorList",
    initialState,
    reducers: {
        addNewOne: (state, action: PayloadAction<dto>) => {
            state = [
                ...state,
                {
                    value: action.payload.value,
                    type: action.payload.type,
                },
            ];
        },
    },
});
export const errorActions = errorListSlice.actions;
export default errorListSlice.reducer;

CodePudding user response:

You cannot reassign the full state object.

In that case, you would have to return.

        addNewOne: (state, action: PayloadAction<dto>) => {
            return [
                ...state,
                {
                    value: action.payload.value,
                    type: action.payload.type,
                },
            ];
        },

But as you already noticed in your answer, you can also .push() on your array - and in Redux Toolkit, that is the preferred way of doing it.

See writing Reducers with immer

CodePudding user response:

It works when I change the reducer in this way. I don´t know if this is maybe a bad practice.

reducers: {
        addNewOne: (state, action: PayloadAction<dto>) => {
            state.push({ value: action.payload.value, type: action.payload.type })
        },
    },
  • Related