Call other slice methods from same slice in redux - redux

I am trying to call other slice methods from the same slice in redux. I tried this approach but TS is throwing errors. What am I doing wrong? (Please see function setInitialLocation)
export const appSlice = createSlice({
name: "app",
initialState,
reducers: {
addCompletedAppSetupSteps: (
state,
action: PayloadAction<AppSetupSteps | AppSetupSteps[]>
) => {
if (Array.isArray(action.payload)) {
state.data.completedAppSetupSteps = union(
state.data.completedAppSetupSteps,
action.payload
);
} else {
state.data.completedAppSetupSteps = union(
state.data.completedAppSetupSteps,
[action.payload]
);
}
},
selectLocation(state, action: PayloadAction<LocationSelection | null>) {
if (!action.payload) {
state.data.selectedLocation = null;
return;
}
const payloadWithDefaults: LocationSelection = {
...action.payload,
settings: {
hasPopup: action.payload?.settings?.hasPopup ?? true,
hasFlyToAnimation:
action.payload?.settings?.hasFlyToAnimation ?? true,
},
};
state.data.selectedLocation = payloadWithDefaults;
},
setInitialLocation(state, action: PayloadAction<LocationSelection>) {
appSlice.caseReducers.selectLocation(state, action); // I am trying to call the other methods here.
appSlice.caseReducers.addCompletedAppSetupSteps(state, {
payload: AppSetupSteps.SetInitialLocationSelection,
type: "addCompletedAppSetupSteps",
});
},
},
});

Related

How to mutation store state in build query redux toolkit

Created an initialState and will be updated the totalPage and currentPage after got the users list.
I found out onQueryStarted from docs, it able to update the store state in this method but only look like only for builder.mutation.
what's the correct way to get the user list and update the store page value in redux toolkit?
Listing two part of the code below:
apiSlice
component to use the hook
// 1. apiSlice
const usersAdapter = createEntityAdapter({})
export const initialState = usersAdapter.getInitialState({
totalPage: 0,
currentPage: 0,
})
export const usersApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
getUsers: builder.query({ // <--- the docs are using builder.mutation, but i needed to pass params
query: (args) => {
const { page, limit } = args;
return {
url: `/api/users`,
method: "GET",
params: { page, limit },
}
},
validateStatus: (response, result) => {
return response.status === 200 && !result.isError
},
transformResponse: (responseData) => { // <<-- return { totalPages: 10, currentPage: 1, users: [{}] }
const loadedUsers = responseData?.users.map((user) => user)
return usersAdapter.setAll(initialState, loadedUsers)
},
async onQueryStarted(arg, { dispatch, queryFulfilled }) {
try {
const { data } = await queryFulfilled
const {totalPages, currentPage} = data; <----- totalPages & currentPage values are still 0 as initialState
dispatch(setPages({ currentPage, totalPages }))
} catch (error) {
console.error("User Error: ", error)
}
},
providesTags: (result, error, arg) => {
if (result?.ids) {
return [
{ type: "User", id: "LIST" },
...result.ids.map((id) => ({ type: "User", id })),
]
} else return [{ type: "User", id: "LIST" }]
},
})
})
});
export const {
useGetUsersQuery,
} = usersApiSlice
component to use the hook
Try to use the hook in user landing page
const UsersList = () => {
const { data: users, isLoading, isSuccess, isError } = useGetUsersQuery({page: 1, limit: 10 })
return (
<div>return the users data</div>
)
}
update the store value after get the data return

Redux Toolkit: How to test actions with uid prepare callback

In the docs for testing incrementing todo ids, this assumes a predictable response.
In an example such as below, a unique id is generated.
How could this be tested?
This test passes, but I'm not sure if it's correct, shouldn't the id be defined based on what's in the prepare callback?
slice.js
add: {
reducer: (state, {payload}: PayloadAction<{id: string, item: Item}>) => {
state[payload.id] = payload.item
},
prepare: (item: Item) => ({
payload: {id: cuid(), item}
})
}
slice.test.js
it('should handle add', () => {
expect(
reducer(
{},
{
type: actions.add,
payload: {
id: 'id-here?',
item: {
other: 'properties...'
}
},
}
)
).toEqual({
'id-here?': {
other: 'properties...'
},
})
})
You can pull out the prepare function and also the reducer function into it's own constant and then test prepare in isolation:
todosSlice.js:
[...]
let nextTodoId = 0;
export const addTodoPrepare = (text) => {
return {
payload: {
text,
id: nextTodoId++
}
}
}
export const addTodoReducer = (state,
action) => {
const {id, text} = action.payload;
state.push({
id,
text,
completed: false
});
};
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: {
prepare: addTodoPrepare,
reducer: addTodoReducer,
},
}
})
[...]
todosSlice.spec.js:
import todos, {addTodo, addTodoPrepare} from './todosSlice'
describe('addTodoPrepare',
() => {
it('should generate incrementing IDs',
() => {
const action1 = addTodoPrepare('a');
const action2 = addTodoPrepare('b');
expect(action1.payload).toEqual({
id: 0,
text: 'a'
})
expect(action2.payload).toEqual({
id: 1,
text: 'b'
})
})
})
describe('todos reducer',
() => {
[...]
})
For unit testing, NO, just test each reducer independently.
For integration testing and e2e testing, Yes.

Redux immutable pattern

I use react with redux.
Action:
export const updateClicked = (id, section) => {
return {
type: actionTypes.UPDATE_CLICKED,
id,
section
};
};
Please advise the best way to immutable update property in nested array:
Reducer:
const initialState = {
updates: {
html: {
id: 'html',
label: 'HTML',
count: 0,
items: [
{
id: 1,
label: 'Header',
price: 10,
bought: false
},
{
id: 2,
label: 'Sidebar',
price: 50,
bought: false
}
]
}
}
};
My action:
action = {
id: 1,
bought: true
}
I want to update bought property inside items array. I.e.:
const updateClicked= (state, action) => {
const updateSections = state.updates[action.section].items;
const updatedItems = updateSections.map(el => {
if (el.id === action.id && !el.bought) {
el.bought = true;
}
return el;
});
//How to update state???
return {}
};
Will be glad if you explain 2 ways to do this:
With es6 spread operator
With some library (like immutability-helper)
Thanks!
With es6 spread operator:
export default (state = initialState, action) => {
if (action.type !== actionTypes.UPDATE_CLICKED) return state;
return {
...state,
updates: {
...state.updates,
html: {
...state.updates.html,
items: state.updates.html.items.map((item, idx) => idx === action.id
? {...item, bought: item.bought}
: item
)
}
}
}
};

Understanding JSON.stringify() on Redux Action?

I was trying to reset the data, and want to go to initial state ,I know that the immutability playing major role in this part.
Below is my store data (Flow Completed data)
animalSense: {
selectedVision: 'dayLight',
selectedState: 'california',
viewedVisions: ['dayLightcalifornia', 'dayLightsouthAfrica', 'nightVisioncalifornia'],
viewedAnimals: ['dog', 'cat']
},
I want to replace it with the below data
animalSense: {
selectedVision: '',
selectedState: '',
viewedVisions: [''],
viewedAnimals: []
},
I know the below action is the Straight and proper way to add initial data is
export const RESET_ANIMAL_SENSES = 'actions/reset_animal_senses';
export default () => ({
type: RESET_ANIMAL_SENSES,
payload: {
selectedVision: '',
selectedState: '',
selectedAnimal: '',
viewedVisions: [''],
viewedAnimals: []
}
});
But the above action maintaining the same state
Below action is Working Solution but I don't know is this a Proper way
export const RESET_ANIMAL_SENSES = 'actions/reset_animal_senses';
const data = JSON.stringify({
selectedVision: '',
selectedState: '',
selectedAnimal: '',
viewedVisions: [''],
viewedAnimals: []
});
export default () => ({
type: RESET_ANIMAL_SENSES,
payload: JSON.parse(data)
});
When we are using stringify the connectivity has been ended and the new state has been added but i don't know why this is not working without JSON.stringify()?
Reducer
import { SELECT_VISION } from '../actions/select_vision_type';
import { CHANGE_ANIMAL_VIDEO_STATE } from '../actions/change_animal_video_state';
import { UPDATE_ANIMALS } from '../actions/update_animals';
import { RESET_ANIMAL_SENSES } from '../actions/reset_animal_senses';
export default (state = {}, action) => {
let newState = state;
switch (action.type) {
case SELECT_VISION:
newState = { ...state, ...action.payload };
break;
case CHANGE_ANIMAL_VIDEO_STATE:
newState = { ...state, ...action.payload };
break;
case UPDATE_ANIMALS:
newState = { ...state, ...action.payload };
break;
case RESET_ANIMAL_SENSES:
newState = { ...state, ...action.payload };
break;
default:
break;
}
return newState;
};
Spread Operator in payload Solved this issue
export const RESET_ANIMAL_SENSES = 'actions/reset_animal_senses';
const data = {
selectedVision: '',
selectedState: '',
selectedAnimal: '',
viewedVisions: [''],
viewedAnimals: []
};
export default () => ({
type: RESET_ANIMAL_SENSES,
payload: { ...data } // here is the solution
});
Try this out, I'd do good amount of refactors to your reducer.
import { SELECT_VISION } from '../actions/select_vision_type';
import { CHANGE_ANIMAL_VIDEO_STATE } from '../actions/change_animal_video_state';
import { UPDATE_ANIMALS } from '../actions/update_animals';
import { RESET_ANIMAL_SENSES } from '../actions/reset_animal_senses';
const initialState = {
selectedVision: '',
selectedState: '',
selectedAnimal: '',
viewedVisions: [''],
viewedAnimals: []
}
export default (state = initialState, action) => {
switch (action.type) {
// since all the cases have common code.
case SELECT_VISION:
case CHANGE_ANIMAL_VIDEO_STATE:
case UPDATE_ANIMALS: {
return { ...state, ...action.payload }
}
case RESET_ANIMAL_SENSES: {
return { ...initialState }
}
default: {
return state;
}
}
};
Try this reducer once. However, currently I don't have a clarity on why would it work with stringify in place.

How to test cyclejs http driver?

Suppose I have an API that return user detail:
/api/get_user/1
{
"status": 200,
"data": {
"username": "username1",
"email": "username#email.com"
}
}
And a "main function" like this:
function main (sources) {
const request$ = sources.ACTIONS
.filter(action => action.type === 'GET_USER_REQUEST')
.map(action => action.payload)
.map(payload => ({
category: 'GET_USER_REQUEST',
url: `${BASE_URL}/api/get_user/${payload.userId}`,
method: 'GET'
}))
const action$ = sources.HTTP
.select('GET_USER_REQUEST')
.flatten()
.map(response => response.data)
const sinks = {
HTTP: request$,
LOG: action$
}
return sinks
}
For testing the "ACTION" source, I can simply made an xstream observable
test.cb('Test main function', t => {
const actionStream$ = xs.of({
type: 'GET_USER_REQUEST',
payload: { userId: 1 }
})
const sources = { ACTION: actionStream$ }
const expectedResult = {
category: 'GET_USER_REQUEST',
url: `${BASE_URL}/api/get_user/${payload.userId}`,
method: 'GET'
}
main(sources).HTTP.addEventListener({
next: (data) => {
t.deepEqual(data, expectedResult)
},
error: (error) => {
t.fail(error)
},
complete: () => {
t.end()
}
})
})
The question is. Is it possible to do the same thing (using plan xstream observable)
to test cycle-http driver without a helper from something like nock?
Or is there a better way to test something like this?
You can mock out the HTTP source like so:
test.cb('Test main function', t => {
const actionStream$ = xs.of({
type: 'GET_USER_REQUEST',
payload: { userId: 1 }
})
const response$ = xs.of({
data: {
status: 200,
data: {
username: "username1",
email: "username#email.com"
}
}
});
const HTTP = {
select (category) {
// if you have multiple categories you could return different streams depending on the category
return xs.of(response$);
}
}
const sources = { ACTION: actionStream$, HTTP }
const expectedResult = {
category: 'GET_USER_REQUEST',
url: `${BASE_URL}/api/get_user/${payload.userId}`,
method: 'GET'
}
main(sources).HTTP.addEventListener({
next: (data) => {
t.deepEqual(data, expectedResult)
},
error: (error) => {
t.fail(error)
},
complete: () => {
t.end()
}
})
})
Really, we should have a mockHTTPSource helper to make this a bit easier. I have opened an issue to that effect. https://github.com/cyclejs/cyclejs/issues/567
If you want to test that certain things happen at the correct time, you could use this pattern in conjunction with #cycle/time.
http://github.com/cyclejs/time

Resources