Reputation: 31
I can't push to the fetchedSpendings state array, which already has data after fetching.
Reducer.js
import {FETCH_SPENDINGS, PUSH_SPENDING } from './types'
const initialState = {
fetchedSpendings: []
}
export const dataReducer = (state = initialState, action) => {
switch(action.type){
case PUSH_SPENDING:
return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}
//return {...state, fetchedSpendings: state.fetchedSpendings = [action.payload]}
case FETCH_SPENDINGS:
return { ...state, fetchedSpendings: action.payload }
default: return state
}
}
Commented out line in case PUSH_SPENDING is working but it does not add data to the array that already contains objects, but replaces them.
//return {...state, fetchedSpendings: state.fetchedSpendings = [action.payload]}
the other in this case does not.
return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}
actions.js
export function fetchSpendings(){
return async dispatch => {
const userid = userDataGetter();
try{
const response = await axios.post('/api/getSpendings', { userID: userid})
const json = await response["data"];
dispatch( {type: FETCH_SPENDINGS, payload: json})
console.log('Returned data:', json);
} catch (e) {
console.log(`Axios request failed in fetchSpendings: ${e}`);
}
}
}
export function pushSpending(cost, category, note){
return async dispatch => {
const userData = userDataGetter();
const userID = userData.userId;
const dataSpend = {
_id: userID,
date: String(new Date()),
cost: cost,
category: category,
note: note
}
try{
const response = await axios.post('/api/addSpending', {cost, category, note, userID})
const json = await response;
dispatch( {type: PUSH_SPENDING, payload: dataSpend})
} catch(e){
console.log(`Axios request failed in pushSpendings: ${e}`);
M.toast({html: "incorrectly entered data"});
}
}
}
in react i am getting error. props.Spending.map is not a function.
Because this line not push data in array.
return {...state, fetchedSpendings: state.fetchedSpendings.push(action.payload)}
Upvotes: 1
Views: 2097
Reputation: 44880
Use the spread operator to create a new array with action.payload
as its final element:
return {
...state,
fetchedSpendings: [...state.fetchedSpendings, action.payload],
}
.push
modifies the array and returns the added element, so fetchedSpendings
is no longer an array when you use .push
. Also, React needs to see a new array to update.
Upvotes: 1