0
votes

I have this dispatch outside of a react component myActions.js:

import {SET_ORDER} from "./defaultActions";
import store from "../store";

const setOrder           = value => ({type: SET_ORDER,value});

export const addToOrder         = (item,type)=>{
    let order   = store.getState().order;//get object from store
    order[type].push(JSON.parse(JSON.stringify(item)));//clone new object to push on order array
    store.dispatch(setOrder(order));//dispatch new order object
};

In my Component i will receive props with:

import {connect} from "react-redux";
import {addToOrder} from "myActions.js";
class Drinks extends Component{
   componentDidMount(){
     this.someAction();//trigger update order
   }
   someAction(){
     addToOrder({something},'type');
   }

   componentWillReceiveProps(props){
     //not works
     //expect props.order but never appears
   }
}

const stateToProps      = ({order}) => ({order});
const dispatchToProps   = null; //not dispatch here


const conn = connect(stateToProps,dispatchToProps);

export default conn(Drinks);

The store it's updated, but componentWillReceiveProps is never called,how i need to do to receive props correctly?

My package redux libraries are: "react-redux": "^5.0.7","redux": "^3.7.2", "redux-thunk": "^2.3.0" my store is work fine between components, only fails when i try to dispatch outside a react component.

1
Are you sure your action is really dispatching? The code you've attached just creates the action object, but never calls dispatch on it (eg. this.props.dispatch(addToOrder(....)) rather than just addToOrder)user2213590
Dispatch is in addOrder function inside myActions.js store.dispatch(setOrder(order));//dispatch new order object, my store is updated, if I print the properties after calling the function x I can see the updated state. but method componentWillReceiveProps is not called.Abel Olguin Chavez

1 Answers

0
votes

You are not really cloning the object (only the item), so you are updating the state in a mutable way which is why componentWillReceiveProps() is never called. Your order variable is still pointing to the order in the redux store. Try this:

export const addToOrder = (item,type) => {
    let order   = {...store.getState().order}; //get cloned order object from store
    order[type].push(item); // push new object to cloned object
    store.dispatch(setOrder(order)); //dispatch new order object
};