Why is redux toolkit not returning state? - react-native

I have a reducer that supposed to return the the orders json object with is_confirmed set to 1. For some reason the code below doesn't return any state at all. The orders state disappears. I am not sure what I am doing wrong. Any help would be highly appreciated.
confirmOrder : (state, action)=> {
const payload = action.payload;
const selected_order_id =payload.selected_order_id;
//console.log(payload.selected_order_id,"id");
return state.orders.map((order)=>{
// console.log(order);
if(selected_order_id === order.id){
return {...order,is_confirmed : 1}
} else {
//console.log(state);
return state;
}
})
}
here is the full code below
const initalState = {orders : []}
const orders = createSlice({
name : "orders",
initialState : initalState,
reducers : {
addToOrders : (state, action)=> {
return {
...state,orders : state.orders.concat(action.payload)
}
},
confirmOrder : (state, action)=> {
const payload = action.payload;
const selected_order_id =payload.selected_order_id;
//console.log(payload.selected_order_id,"id");
return state.orders.map((order)=>{
// console.log(order);
if(selected_order_id === order.id){
return {...order,is_confirmed : 1}
} else {
//console.log(state);
return state;
}
})
}
}
})
export const {addToOrders,confirmOrder} = orders.actions;
export default orders.reducer;

confirmOrder : (state, action)=> {
const payload = action.payload;
const selected_order_id =payload.selected_order_id;
//console.log(payload.selected_order_id,"id");
return state.orders.map((order)=>{
// console.log(order);
if(selected_order_id === order.id){
return {...order,is_confirmed : 1}
} else {
//console.log(state);
return state;
}
})
}

Related

How can I alter my redux action and reducer to have array with objects in it?

I have currently redux action and reducer that allows me to add or remove items from the array. Now I want to add more items in following format. [{id: , car: '', text: '', box1Checked: '', box2Checked: '', box3Checked: ''}]
This is the form I have.
this is my current action file:
const ADD_NEW_CAR = 'ADD_NEW_CAR'
const DELETE_EXISTING_CAR = 'DELETE_EXISTING_CAR'
export const addNewCar = (text) => ({
type: ADD_NEW_CAR,
payload: text
})
export const deleteExistingCar = (car) => ({
type: DELETE_EXISTING_CAR,
payload: car
})
this is the reducer:
const ADD_NEW_CAR = 'ADD_NEW_CAR'
const DELETE_EXISTING_CAR = 'DELETE_EXISTING_CAR'
const initialState = {
cars: [],
}
const carsListReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_NEW_CAR:
return {
...state,
cars: [...state.cars, action.payload],
}
case DELETE_EXISTING_CAR:
return {
cars: [
...state.cars.filter(car => car !== action.payload)
]
}
default:
return state
}
}
export default carsListReducer
This is where i call the function to add cars.
const addCarDetails = () => {
if (newCar.length > 0) {
// setCars([
// ...cars,
// {
// id: cars.length + 1,
// license: newCar,
// },
// ])
props.addNewCar(newCar)
setValid(true)
setNewCar('')
carAddedToast()
} else {
setValid(false)
}
}
const removeCar = (item) => {
props.deleteExistingCar(item)
//setCars(cars.filter((item) => item.license !== license))
carRemovedToast()
}
To change any reducer value, you need to dispatch an action with the dispatch() method.
// Top-level import
import {useDispatch} from 'rect-redux'
// Inside a functional component
const dispatch = useDispatch()
const addCarDetails = () => {
if (newCar.length > 0) {
// dispatch add new car action to associated reducer
dispatch(props.addNewCar(newCar))
setValid(true)
setNewCar('')
carAddedToast()
} else {
setValid(false)
}
}
const removeCar = (item) => {
// dispatch remove a car action to associated reducer
dispatch(props.deleteExistingCar(item))
carRemovedToast()
}
The problem was solved using following. It was really small change that was needed.
case ADD_NEW_CAR:
return {
...state,
cars: [...state.cars, {id: state.cars.length, ...action.payload}],
}

swimlane/ngx-datatable, How can I kick the cellClass function?

The cellClass function is not called when the component properties change.
How do I kick a rowClass orcellClass?
#Component({
...,
template: `<ngx-datatable [rowClass]="rowClass"></ngx-datatable>`
})
class SomeComponent {
someVariable = true;
rowClass = (row) => {
return {
'some-class': (() => { return this.someVariable === row.someVariable })()
};
}
}
Related
https://github.com/swimlane/ngx-datatable/issues/774
I was able to solve it by changing this.rows.
https://swimlane.gitbook.io/ngx-datatable/cd
this.rows = [...this.rows];
If you are using a store, you need to cancel the immutable attribute.
Example
#Input() set list(list: Record<string, unknown>[]) {
if (list.length) {
// If the search results are reflected in the table.
// And 20 items are loaded at a time.
if (list.length === 20) {
this.rows = list.map((item) => ({ ...item }));
// Load more items
} else {
const newRows = list.map((item) => ({ ...item })).slice(this.rows.length);
this.rows = this.rows.concat(newRows);
}
}
}

ngrx store state undefined

I am not sure why my state in my store is undefined when I try to access it. I have been looking at this for sometime now and I cannot figure it out.
my actions are
export const GetMerchants = createAction('[Merchant] - Get Merchants');
export const GetMerchantsSuccess = createAction(
'[Merchant] - Get Merchants Success',
props<{ payload: Merchant[] }>()
);
export const GetMerchantsFailure = createAction(
'[Merchant] - Get Merchants Failure',
props<{ payload: Error }>()
);
My reducers and state def are
export default class MerchantListState {
merchants: Array<Merchant>;
merchantError: Error;
}
export const initializeMerchantListState = (): MerchantListState => {
return {
merchants: new Array<Merchant>(),
merchantError: null
};
};
export const intialMerchantListState = initializeMerchantListState();
const _reducer = createReducer(
intialMerchantListState,
on(actions.GetMerchants, (state: MerchantListState) => {
return {
...state
};
}),
on(actions.GetMerchantsSuccess, (state: MerchantListState, { payload }) => {
let newstate = { ...state,
merchants: [ ...state.merchants, payload],
merchantError: null
};
return newstate;
}),
on(actions.GetMerchantsFailure, (state: MerchantListState, { payload }) => {
console.log(payload);
return { ...state, merchantError: payload };
}),
);
export function merchantListReducer(state: MerchantListState, action: Action) {
return _reducer(state, action);
}
My effects
#Injectable()
export class MerchantListEffects {
constructor(private apiService: ApiService, private apiRouteService: ApiRouteService, private action$: Actions) { }
GetMerchants$: Observable<Action> = createEffect(() =>
this.action$.pipe(
ofType(actions.GetMerchants),
mergeMap(action => this.apiService.get(this.apiRouteService.toMerchants()).pipe(
map((data: Merchant[]) => { console.log(data); return actions.GetMerchantsSuccess({ payload: data }); }
), catchError((error: Error) => { return of(actions.GetMerchantsFailure({ payload: error })) })
)
)));
}
When I inject the state into the component
private store: Store<{ merchantList: MerchantListState }>
I get an undefined merchant$ observable when I try to do this
this.merchants$ = store.pipe(select('merchantList'));
this.merchantSubscription = this.merchants$.pipe(
map(x => {
console.log(x.merchants);
})
)
.subscribe();
On a button click I am loading the merchants with this dispatch
this.store.dispatch(actions.GetMerchants());
I have my reducer and effects defined in AppModule
StoreModule.forRoot({ merchantList: merchantListReducer }),
EffectsModule.forRoot([MerchantListEffects])
Is it something that I am missing?
First Parameter of createReducer is a value, not a function.
API > #ngrx/store
createReducer
If you use a function, you have to call it:
const _reducer = createReducer(
intialMerchantListState()
I prefare the way to define direct a value initialState:
export const initializeMerchantListState: MerchantListState = {
merchants: new Array<Merchant>(),
merchantError: null
};

Cannot pass multiple arguments in vuex actions

I'm trying to call vuex action in vue component with multiple parameters. But in action method cannot access these passed arguments.
I have already tried passing value in payload as object which is mostly suggested here. but still it is not working.
Please look for
this.getMessageFromServer(payload);
MessageBox.vue
import Vue from 'vue';
import { mapGetters, mapActions } from 'vuex';
import MessageView from './MessageView.vue';
export default Vue.component('message-box',{
components:{
MessageView
},
data() {
return {
messageList :[],
}
},
created() {
this.fetchTimeMessage();
console.log("reaching inside ");
},
computed:{
...mapGetters(['getMessage','getActiveMessageData']),
...mapActions(['getMessageFromServer']),
},
methods: {
fetchTimeMessage:function(){
console.log("fetchTimeMessage : ");
var messageUser = this.getMessage.findIndex((e) => e.muid == this.getActiveMessageData.id);
console.log("fetchTimeMessage : " , {messageUser});
if (messageUser == -1) {
let user_id = this.getActiveMessageData.id;
let user_type = this.getActiveMessageData.type;
console.log("inside fetch Message : " + user_id);
console.log("inside fetch Message : " + user_type);
const payload = {
'uType': user_type,
'uid' : user_id,
'limit': 50
};
this.getMessageFromServer(payload);
}
},
},
});
Vuex modules message.js
const state = {
messages:[],
activeMessage : {}
};
const getters = {
getActiveUserId: (state) => {
let activeUserId = "";
if (!utils.isEmpty(state.activeMessage)) {
activeUserId = state.activeMessage.id;
}
return activeUserId;
},
getActiveMessage:(state) => { return !utils.isEmpty(state.activeMessage);},
getActiveMessageData : (state) => {return state.activeMessage } ,
getMessage: (state) => {return state.messages},
};
const actions = {
getMessageFromServer({ commit, state },{utype,uid,limit}){
console.log("mesage callback asdas : " + uid);
let messageRequest = CCManager.messageRequestBuilder(utype, uid, limit);
messageRequest.fetchPrevious().then(messages => {
//console.log("mesage callback : " + JSON.stringify(messages));
// handle list of messages received
let payload = {
'messsages':messages,
'id': uid
};
console.log("inside action_view : " + JSON.stringify(payload));
//commit('updateMessageList',payload);
})
},
setActiveMessages:function({commit},data){
commit('updateActiveMessage',data);
},
};
const mutations = {
updateMessageList(state,{messages,id}){
console.log("action details" + id);
//uid is not present
var tempObj = {
'muid' : id,
'message' : messages
}
state.messages.push(tempObj);
}
},
updateActiveMessage(state,action){
state.activeMessage = {
type: action.type,
id: action.uid
};
}
};
export default {
state,
getters,
actions,
mutations
};
Change the way you call the action in your component:
this.$store.dispatch('getMessageFromServer', payload);
And pass the payload as a single object in your action function:
getMessageFromServer({ commit, state }, payload)
And you can then access the payload properties in the action like this:
getMessageFromServer({ commit, state }, payload) {
var uid = payload.uid;
var uType = payload.uType;
var limit = payload.limit;
}

How to fix the navigation

I’m setting up a new service for navigation to "Chat" service but it doesn't do anything and I don't know why.
This is for a new component
here is the "onCancel" button that use the "getCustomerService" function..
handleUnrecognizedUser = () => {
const infoMsg = {
onCancel: getCustomerService
};
};
here is the "getCustomerService" function that get called
import { AppStore, RoutingStore } from '../../stores'
import call from 'react-native-phone-call'
callServeiceCenter = (number) => {
const args = {
number, // String value with the number to call
prompt: false // Optional boolean property. Determines if the user should be prompt prior to the call
}
return call(args).catch(console.error)
}
export default getCustomerService = () => {
if (AppStore.isWorkingHours)
RoutingStore.goTo('Chat')
else {
callServeiceCenter(AppStore.getCallCenterPhone)
}
}
this is for the "RoutingStore" :
import { observable, action, computed } from "mobx";
import { NavigationActions, StackActions, DrawerActions } from 'react-navigation'
class RoutingStore {
#observable nav = null;
#observable PrevPage = null;
#observable curentPage = null;
#observable isGoBackAvailable = true;
#observable isLoggedIn = false;
#action
setNavigation(data) {
this.nav = data
}
goTo = (data, _params) => {
let { routeName, params } = data
const navigateAction = NavigationActions.navigate(
routeName
? { routeName, params }
: { routeName: data, params: { ..._params } })
this.nav.dispatch(navigateAction)
}
#action
goBack = () => {
}
#action
updateCurrentPage(data) {
this.curentPage = data
}
#action
updatePrevPage(data) {
this.PrevPage = data
}
updatePages = (prev, cur) => {
this.updatePrevPage(prev)
this.updateCurrentPage(cur)
}
#action
setLoggedIn(status) {
this.isLoggedIn = status
}
#action
openDrawer() {
this.nav.dispatch(DrawerActions.openDrawer())
}
#action
closeDrawer() {
this.nav.dispatch(DrawerActions.closeDrawer())
}
#action
toggleDrawer() {
this.nav.dispatch(DrawerActions.toggleDrawer())
}
disableLoginRoute = (route) => {
const resetAction = StackActions.reset({
index: 0,
key: null,
actions: [NavigationActions.navigate({ routeName: route })],
});
this.nav.dispatch(resetAction)
}
isGoBackAllowed = () => {
switch (this.curentPage) {
case "Tabs": return false
case "Login": return false
default: return this.goBack()
}
}
#computed
get isNonLogin() {
return this.isLoggedIn;
}
#computed
get getCurentPage() {
return this.curentPage;
}
}
const routingStore = new RoutingStore();
export default routingStore;
I expect to navigate to the Chat as well.