Home > Enterprise >  Why does dispatching action rewrite my store value?
Why does dispatching action rewrite my store value?

Time:11-13

I'm dispatching twice to the redux store from my functional component using redux hooks.

When I dispatch these individually like this only one of them is stored in my redux store as it seems to refresh each time and only keep one. How can I dispatch these together or prevent the redux store from refreshing and losing the first dispatch payload??

dispatch({
              type: "access_token",
              payload: googleUser.accessToken,
            });
            dispatch({
              type: "firebase_userId",
              payload: result.user.uid,
            });

Redux store

import React from "react";
import symbolicateStackTrace from "react-native/Libraries/Core/Devtools/symbolicateStackTrace";
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";

const initialState = {
  access_token: "",
  firebase_userId: "",
};

const counterReducer = (
  state = initialState,
  action
) => {
 
 

  if (action.type === "access_token") {
 
    return {
      
      access_token: action.payload,
    };
  }

  if (action.type === "firebase_userId") {
  
    return {
     
      firebase_userId: action.payload,
    };
  }

  return state;
};

const store = createStore(counterReducer, applyMiddleware(thunk));

export default store;


CodePudding user response:

In your reducer, you always need to return a copy of current state. That's the problem. Nothing wrong with how you dispatch actions.

const counterReducer = (
  state = initialState,
  action
) => {

  if (action.type === "access_token") {
 
    return {
      // copy & update state
      ...state,
      access_token: action.payload,
    };
  }

  if (action.type === "firebase_userId") {
  
    return {
     // copy & update state
     ...state,
      firebase_userId: action.payload,
    };
  }

  return state;
};
  • Related