I'm trying to update the cart-button on a project when the user adds an item to the cart.
I have build parts of the site in React.js - like the cart, the cart button etc.
configureStore.js:
export default function configureStore(initialState) {
const store = createStore(
reducers,
initialState
return store
}
Action:
export function updateCart(payload) {
return {
type: CART_UPDATE,
payload: payload
}
}
Reducer:
export default function cart(state = {}, action) {
switch (action.type) {
case CART_UPDATE:
const cart = {
data: action.payload.cart,
errors: action.payload.errors,
isFetching: false
};
return {
...state,
...cart
};
return state;
}
CartButton.js
... componnent etc.
function mapStateToProps(state) {
return {
cart: state.cart.data
};
}
export default connect(mapStateToProps)(CartButton);
Provider
import configureStore from './store/configureStore'
var store = configureStore();
ReactDOM.render((<Provider store={store}><Cart showControls={true} /></Provider>), document.getElementById('react-cart'));
I'm dispatching an action that is supposed to update the cart quantity from a non-react component like this:
// imports
import { dispatch } from 'redux';
import { updateCart } from '../../actions/cart_actions';
import configureStore from '../../store/configureStore'
var store = configureStore();
and then..
store.dispatch(updateCart(response));
The action is dispatched and the state is updated. The cart-button component is connected via. react-redux connect() function. But somehow it isn't updating the component with the new quantity.
When I dispatch an action from within my cart React component it works fine.
I might be missing something obvious. Any suggestions?
To trigger a Redux action from outside a component with React, we call store. dispatch from anywhere in our project. import { store } from "/path/to/createdStore"; function testAction(text) { return { type: "TEST_ACTION", text, }; } store.
If you need to dispatch actions from outside a React component, the same technique will work: import the store, then call store. dispatch() , passing the action you need to dispatch. It works the same as the dispatch function you get from props via react-redux's connect function.
Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.
So what I ended up figuring out is that you shouldn't define your store in more than one place.
I simply imported the store constant from my root app.js-file like this:
import { store } from './app';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With