Search code examples
react-nativereduxreact-reduxredux-toolkit

@reduxjs/toolkit State Update Issue


I just started learning react-native. I'm also working on reduxjs/toolkit. I wanted to do a simple exercise to find out. What I want to do is increase the number by 1 when I press the button. Unfortunately, I was not able to achieve this increase. How can i solve this problem.


import React from "react";
import { View, Text, Button } from "react-native";
import { Provider, useDispatch, useSelector } from "react-redux";
import {
  legacy_createStore,
  createSlice,
  createAction,
  combineReducers
} from "@reduxjs/toolkit";

const incrementBy = createAction('incrementBy')

const counter = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
    multiply: {
      reducer: (state, action) => state * action.payload,
      prepare: (value) => ({ payload: value || 2 })
    },
  },
  extraReducers: (builder) => {
    builder.addCase(incrementBy, (state, action) => {
      return state + action.payload;
    })
  },
})

const reducer = combineReducers({
  counter: counter.reducer,
})

const store = legacy_createStore(reducer)

export default () => {
  return (
    <Provider store={store}>
      <View style={{ flex: 1 }}>
        <First />
        <Second />
      </View>
    </Provider>
  );
};

const First = () => {
  const counter = store.getState().counter;
  return (
    <View style={{ flex: 1, backgroundColor: "black" }}>
      <Text style={{ color: "white", fontSize: 40 }}>First : {counter}</Text>
    </View>
  );
};

const Second = () => {

  const counter = useSelector(state => state.counter);
  const dispatch = useDispatch();

  return (`your text`
    <View style={{ flex: 1 }}>
      <Text style={{ fontSize: 40 }}>Second : {counter}</Text>
      <Button title="+" onPress={() => dispatch(increment())} />
    </View>
  );
};

Solution

  • There's a couple issues here.

    First, you shouldn't be importing the store directly into any component files.

    Second, you also shouldn't be calling store.getState() in a component, because that doesn't subscribe to updates. You should be using useSelector, which is what you have in the other component.

    It looks like the <Second> component ought to re-render okay.

    Also, while it's not directly related to this issue: you should not be calling legacy_createStore - instead, you should be using the configureStore method from Redux Toolkit instead.

    More details: