I'm using Redux in my React App, currently only have 1 reducer at the moment for a Portfolio of cryptocurrencies. Just an array of coins.
When I dispatch my ADD_COIN action the first time I get back an Array of 1 object which is expected. However when I call dispatch again on another coin it returns the Array again, but still only with 1 item, the latest coin that was selected.
How would this need to be re-written to return back the updated Array with all added coins?
2nd coin added, expected to see an Array with 2 objects:
const store = createStore(reducer, compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));
import { combineReducers } from 'redux'
import portfolio from './portfolio'
export default combineReducers({
portfolio
});
import * as R from 'ramda'
import * as api from '../../services/api'
import { addToPortfolio, getPortfolio } from '../../services/coinFactory'
export const ADD_COIN = 'ADD_COIN'
export function addCoin(coin) {
return dispatch =>
api.getCoin(coin)
.then((res) => addToPortfolio(R.head(res.data)))
.then((portfolio) => dispatch(add(portfolio)));
}
//action creator
export function add(portfolio) {
return {
type: ADD_COIN,
portfolio
}
}
import { ADD_COIN } from './actions'
const initialState = [];
export default (state = initialState, action) => {
switch(action.type) {
case ADD_COIN:
return action.portfolio;
default:
return state;
}
}
import * as R from 'ramda'
import local_coins from '../coins.json'
export const storage = {
coins: local_coins,
portfolio: []
};
export const getPortfolio = () => storage.portfolio;
export const addToPortfolio = (coin) => {
storage.portfolio.push(coin);
return getPortfolio();
};
Instead of mutating your initialState with .push
, "copy" your last state into meaningful new state
import { ADD_COIN } from './actions'
const initialState = [];
export default (state = initialState, action) => {
switch(action.type) {
case ADD_COIN:
return [...state, action.portfolio]; // same as state.concat(action.portfolio)
default:
return state;
}
}