Exporting extra reducers from redux toolkit - reactjs

I made a todo list a while ago as a way to practice react and redux. Now I'm trying to rewrite it with redux toolkit and having some trouble with the action creators.
Here is the old actions creator:
export const changeDescription = (event) => ({
type: 'DESCRIPTION_CHANGED',
payload: event.target.value })
export const search = () => {
return (dispatch, getState) => {
const description = getState().todo.description
const search = description ? `&description__regex=/${description}/` : ''
axios.get(`${URL}?sort=-createdAt${search}`)
.then(resp => dispatch({ type: 'TODO_SEARCHED', payload: resp.data }))
} }
export const add = (description) => {
return dispatch => {
axios.post(URL, { description })
.then(() => dispatch(clear()))
.then(() => dispatch(search()))
} }
export const markAsDone = (todo) => {
return dispatch => {
axios.put(`${URL}/${todo._id}`, { ...todo, done: true })
.then(() => dispatch(search()))
} }
export const markAsPending = (todo) => {
return dispatch => {
axios.put(`${URL}/${todo._id}`, { ...todo, done: false })
.then(() => dispatch(search()))
} }
export const remove = (todo) => {
return dispatch => {
axios.delete(`${URL}/${todo._id}`)
.then(() => dispatch(search()))
} }
export const clear = () => {
return [{ type: 'TODO_CLEAR' }, search()] }
Now this is the one that I'm working on, I'm trying to replicate the actions of the old one but using redux toolkit:
export const fetchTodos = createAsyncThunk('fetchTodos', async (thunkAPI) => {
const description = thunkAPI.getState().todo.description
const search = description ? `&description__regex=/${description}/` : ''
const response = await axios.get(`${URL}?sort=-createdAt${search}`)
return response.data
})
export const addTodos = createAsyncThunk('fetchTodos', async (thunkAPI) => {
const description = thunkAPI.getState().todo.description
const response = await axios.post(URL, {description})
return response.data
})
export const todoReducer = createSlice({
name: 'counter',
initialState: {
description: '',
list: []
},
reducers: {
descriptionChanged(state, action) {
return {...state, dedescription: action.payload}
},
descriptionCleared(state, action) {
return {...state, dedescription: ''}
},
},
extraReducers: builder => {
builder
.addCase(fetchTodos.fulfilled, (state, action) => {
const todo = action.payload
return {...state, list: action.payload}
})
.addCase(addTodos.fulfilled, (state, action) => {
let newList = state.list
newList.push(action.payload)
return {...state, list: newList}
})
}
})
The thing is, I can't find anywhere how to export my extra reducers so I can use them. Haven't found anything in the docs. Can someone help?

extraReducers
Calling createSlice creates a slice object with properties reducers and actions based on your arguments. The difference between reducers and extraReducers is that only the reducers property generates matching action creators. But both will add the necessary functionality to the reducer.
You have correctly included your thunk reducers in the extraReducers property because you don't need to generate action creators for these, since you'll use your thunk action creator.
You can just export todoReducer.reducer (personaly I would call it todoSlice). The reducer function that is created includes both the reducers and the extra reducers.
Edit: Actions vs. Reducers
It seems that you are confused by some of the terminology here. The slice object created by createSlice (your todoReducer variable) is an object which contains both a reducer and actions.
The reducer is a single function which takes the previous state and an action and returns the next state. The only place in your app when you use the reducer is to create the store (by calling createStore or configureStore).
An action in redux are the things that you dispatch. You will use these in your components. In your code there are four action creator functions: two which you created with createAsyncThunk and two which were created by createSlice. Those two will be in the actions object todoReducer.actions.
Exporting Individually
You can export each of your action creators individually and import them like:
import {fetchTodos, descriptionChanged} from "./path/file";
Your fetchTodos and addTodos are already exported. The other two you can destructure and export like this:
export const {descriptionChanged, descriptionCleared} = todoReducer.actions;
You would call them in your components like:
dispatch(fetchTodos())
Exporting Together
You might instead choose to export a single object with all of your actions. In order to do that you would combine your thunks with the slice action creators.
export const todoActions = {
...todoReducer.actions,
fetchTodos,
addTodos
}
You would import like this:
import {todoActions} from "./path/file";
And call like this:
dispatch(todoActions.fetchTodos())

Related

Why do I have an error: 'Actions must be plain objects. Use custom middleware for async actions.' when using redux?

So I have a movie app, and I have a page for a single movie. I have a section on that page where I display all of the videos from an API related to a certain movie.
So my Videos component looks like this:
const Videos = ({videos} :{videos:IVideos | null}) => {
return (
<div>{videos?.results.map((video, i) =>
<div key={i}>{video.name}</div>
)}</div>
)
}
It's just a basic component which gets props from a higher component. But the main thing is redux slice, which looks like this:
Initial state:
const initialState: IMovieVideosState = {
movieVideos: null,
fetchStatus: null,
}
export interface IMovieVideosState {
movieVideos: IVideos | null;
fetchStatus: FetchStatus | null;
}
And finally slice:
const videosSlice = createSlice({
name:'videos',
initialState,
reducers:{},
extraReducers(builder) {
builder
.addCase(fetchVideos.pending, (state, action) => {
state.fetchStatus = FetchStatus.PENDING
})
.addCase(fetchVideos.fulfilled, (state, action) => {
state.fetchStatus = FetchStatus.SUCCESS
state.movieVideos = action.payload
})
.addCase(fetchVideos.rejected, (state, action) => {
state.fetchStatus = FetchStatus.FAILURE
//state.error = action.error.message
})
}
})
As you see, these are basic reducers, where if promise is successful I assign payload to an existing array.
And also thunk function:
export const fetchVideos = createAsyncThunk('videos/fetchVideos', async (id: number) => {
const response = await axios.get<IVideos>(`${API_BASE}movie/${id}/videos?api_key=${TMDB_API_KEY}`);
console.log(response.data);
return response.data;
})
But in the browser I have the next error:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
And also another one:
A non-serializable value was detected in an action, in the path: `<root>`. Value:
Promise { <state>: "pending" }
Take a look at the logic that dispatched this action:
Promise { <state>: "pending" }
I have no idea why I could have these errors, because my reducer is the same as another one in my project, but this one doesn't work for some reason.
UseEffect for dispatching all reducers:
useEffect(() =>{
dispatch(fetchDetail(Number(id)));
dispatch(fetchCredits(Number(id)));
dispatch(fetchPhotos(Number(id)));
dispatch(fetchRecommended(Number(id)));
dispatch(fetchSimilar(Number(id)));
dispatch(fetchVideos(Number(id))); //dispatching fetchVideos()
}, [dispatch, id])
So in my case, all of the other functions work fine besides fetchVideos().
Another example of a thunk for movie details:
export const fetchDetail = createAsyncThunk('detail/fetchDetail', async (id: number) => {
const response = await axios.get<IMovie>(`${API_BASE}movie/${id}?api_key=${TMDB_API_KEY}`);
console.log(response.data);
return response.data;
})
My store file:
import thunk from "redux-thunk";
export const store = configureStore({
reducer: {
popular,
top_rated,
playing,
upcoming,
detail,
credits,
videos,
photos,
recommended,
similar
},
middleware: [thunk]
})
export type RootState = ReturnType<typeof store.getState>;
instead of using create Async Thunk method add think malware where you create store of videos then you can pass Async actions into it without nothing.
import { applyMiddleware, combineReducers, createStore } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
// import your videos reducer here from file
export interface State {
videos: IVideos;
}
const rootReducer = combineReducers<State>({
videos: VideosReducer,
});
export const rootStore = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);

How to subscribe to state outside React component in Redux Toolkit?

I have the following slice:
export const authenticationSlice = createSlice({
name: 'authentication',
initialState: {
isFirstTimeLoading: true,
signedInUser: null
},
reducers: {
signOut: (state) => {
state.signedInUser = null
},
setUserAfterSignIn: (state, action: PayloadAction<SignInResult>) => {
// some logic...
state.signedInUser = {...}
}
},
extraReducers: builder => {
// Can I subscribe to signedInUser changes here?
}
})
Is there a way I can subscribe to when signedInUser changes (setUserAfterSignIn and signOut), inside extraReducers?
For example everytime the setUserAfterSignIn action is dispatched I want to add an interceptor in axios that uses the user's accessToken as a Auth header.
Can I also subscribe to this state from antoher slice? if some state in a different slice depends on signedInUser?
EDIT: Here is the thunk that signs in a user, and one that signs out
export const { signOut: signOutAction, setUserAfterSignIn: setUserAction } = authenticationSlice.actions
export const signInWithGoogleAccountThunk = createAsyncThunk('sign-in-with-google-account', async (staySignedIn: boolean, thunkAPI) => {
const state = thunkAPI.getState() as RootState
state.auth.signedInUser && await thunkAPI.dispatch(signOutThunk())
const googleAuthUser = await googleClient.signIn()
const signedInUser = await signInWithGoogleAccountServer({ idToken: googleAuthUser.getAuthResponse().id_token, staySignedIn })
thunkAPI.dispatch(setUserAction({ data: signedInUser.data, additionalData: { imageUrl: googleAuthUser.getBasicProfile().getImageUrl() } } as SignInResult))
})
export const signInWithLocalAccountThunk = createAsyncThunk('sign-in-with-local-account', async (dto: LocalSignInDto, thunkAPI) => {
const state = thunkAPI.getState() as RootState
state.auth.signedInUser && await thunkAPI.dispatch(signOutThunk())
const user = await signInWithLocalAccountServer(dto)
thunkAPI.dispatch(setUserAction({ data: user.data } as SignInResult))
})
export const signOutThunk = createAsyncThunk<void, void, { dispatch: AppDispatch }>('sign-out', async (_, thunkAPI) => {
localStorage.removeItem(POST_SESSION_DATA_KEY)
sessionStorage.removeItem(POST_SESSION_DATA_KEY)
const state = thunkAPI.getState() as RootState
const signedInUser = state.auth.signedInUser
if (signedInUser?.method === AccountSignInMethod.Google)
await googleClient.signOut()
if (signedInUser)
await Promise.race([signOutServer(), rejectAfter(10_000)])
.catch(error => console.error('Signing out of server was not successful', error))
.finally(() => thunkAPI.dispatch(signOutAction()))
})
Redux implements the flux architecture.
This structure allows us to reason easily about our application in a way that is reminiscent of functional reactive programming, or more specifically data-flow programming or flow-based programming, where data flows through the application in a single direction — there are no two-way bindings.
Reducers should not be dependent on each other, because redux does not ensure a specific order in which they are executed. You can work around this by using combineReducer. You can not be sure that the extraReducers are executed after the setUserAfterSignIn reducer.
The options you have are:
Put the code that updates the axios interceptor in the setUserAfterSignIn reducer.
setUserAfterSignIn: (state, action: PayloadAction<SignInResult>) => {
// some logic...
state.signedInUser = {...}
// update axios
}
Create the axios interceptor and pass it a supplier that is connected to the store. This way you can replace the way tokens are supplied easily.
const tokenSupplier = () => store.getState().signedInUser;
// ...
axios.interceptors.request.use(function (config) {
const token = tokenSupplier();
config.headers.Authorization = token;
return config;
});
Extract two reducer functions and ensure their order.
function signInUser(state, action) {
state.signedInUser = {...}
}
function onUserSignedIn(state, action) {
// update axios interceptor
}
// ....
// ensure their order in the redux reducer.
setUserAfterSignIn: (state, action: PayloadAction<SignInResult>) => {
signInUser(state, action);
onUserSignedIn(state, action)
}
EDIT
Given this architecture, What are my options if I have another slice that needs to react when signedInUser has changed?
I guess you will not like the answer. I struggled with the same issue some time ago.
Another slice is an independent part in the store. You can add extra reducers that can listen to actions from other slices, but you can not be sure that the other slice's reducer has already updated the state.
Let's assume you have a slice A and a reducer RA and a slice B with a reducer RB. If the state B depends on A it means that the reducer RB should execute whenever A changes.
You can RA call RB, but this introduces a dependency to RB. It would be nice if RA could dispatch an action like { type: "stateAChanged", payload: stateA} so that other slices can listen to that action, but reducers can not dispatch actions. You can implement a middleware that augments actions with a dispatcher. E.g.
function augmentAction(store, action) {
action.dispatch = (a) => {
store.dispatch(a)
}
store.dispatch(action)
}
so that the reducers can dispatch actions.
setUserAfterSignIn: (state, action: PayloadAction<SignInResult>) => {
// some logic...
state.signedInUser = {...}
action.dispatch({type : "userSignedIn": payload: {...state}})
}
But this approach is not a standard approach and if you excessively use it, you might introduce cycles that lead to endless loops in the dispatch.
Instead of using different slices some use different stores and connect them using the store's subscribe. This is an official AP, but it can also introduce loops if you don't pay enough attention.
So finally the simplest approach is to just call RB from RA. You can manage the dependency between them a bit by reversing it. E.g.
const onUserSignedIn = (token) => someOtherReducer(state, { type: "updateAxios", payload: token});
setUserAfterSignIn: (state, action: PayloadAction<SignInResult>) => {
// some logic...
state.signedInUser = {...}
onUserSignedIn(state.signedInUser.token)
}
Now you can replace the onUserSignedIn callback in tests or with a composite functions that calls other registered callbacks.
EDIT
I'm currently working on a middleware library to solve our issue. I published my actual version of my library on Github and npm. The idea is that you describe the dependencies between states and actions that should be dispatched on change.
stateChangeMiddleware
.whenStateChanges((state) => state.counter)
.thenDispatch({ type: "text", payload: "changed" });
Yes, another slice can listen for various action types and apply the action payload (or meta data) to its own state object.
But be careful that you don't end up keeping mirrored or derived state spread across various slices of your store.
export const signInThunk = createAsyncThunk('signIn', async (_: void, thunkAPI) => {
const authUser = await authClient.signIn()
return authUser
})
export const authenticationSlice = createSlice({
name: 'authentication',
initialState: {
isFirstTimeLoading: true,
signedInUser: null
},
reducers: {},
extraReducers: builder => {
builder.addCase(signInThunk.fulfilled, (state, action) => {
state.signedInUser = action.payload
})
}
})
export const anotherSlice = createSlice({
name: 'another',
initialState: {},
reducers: {},
extraReducers: builder => {
builder.addCase(signInThunk.fulfilled, (state, action) => {
// do something with the action
})
}
})

Redux: Call thunk action from slice reducer action

I have a tree structure which is loading children on demand, this is my reducer. The problem I have is that when I want to call my thunk action from toggleExpandedProp I get exception (see bellow). What should I do?
import { createSlice, createAsyncThunk } from '#reduxjs/toolkit';
import { useDispatch } from 'react-redux';
import axios from 'axios';
const dispatch = useDispatch()
export const getRoot = createAsyncThunk('data/nodes/getRoot', async () => {
const response = await axios.get('http://localhost:5000/api/nodes/root');
const data = await response.data;
return data;
});
export const getChildren = createAsyncThunk('data/nodes/getRoot', async params => {
const response = await axios.get('http://localhost:5000/api/nodes/' + params.id + '/children');
const data = await response.data;
return data;
});
const initialState = {
data: [],
loading: 'idle'
};
// Then, handle actions in your reducers:
const nodesSlice = createSlice({
name: 'nodes',
initialState,
reducers: {
toggleExpandedProp: (state, action) => {
state.data.forEach(element => {
if(element.id === action.payload.id) {
element.expanded = !element.expanded;
dispatch(getChildren(element));
}
});
}
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[getRoot.fulfilled]: (state, action) => {
state.data = action.payload;
},
[getChildren.fulfilled]: (state, action) => {
state.data.push(action.payload);
}
}
})
export const { toggleExpandedProp } = nodesSlice.actions;
export default nodesSlice.reducer;
Exception has occurred.
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
const dispatch = useDispatch()
You can only use useDispatch inside of a function component or inside another hook. You cannot use it at the top-level of a file like this.
You should not call dispatch from inside a reducer. But it's ok to dispatch multiple actions from a thunk. So you can turn toggleExpandedProp into a thunk action.
You probably need to rethink some of this logic. Does it really make sense to fetch children from an API when expanding a node and then fetch them again when collapsing it?
export const toggleExpandedProp = createAsyncThunk(
"data/nodes/toggleExpandedProp",
async (params, { dispatch }) => {
dispatch(getChildren(params));
}
);
This is kind of a useless thunk since we don't actually return anything. Can you combine it with the getChildren action, or do you need to call that action on its own too?
const nodesSlice = createSlice({
name: "nodes",
initialState,
reducers: {
},
extraReducers: {
[toggleExpandedProp.pending]: (state, action) => {
state.data.forEach((element) => {
if (element.id === action.payload.id) {
element.expanded = !element.expanded;
}
});
},
[getRoot.fulfilled]: (state, action) => {
state.data = action.payload;
},
[getChildren.fulfilled]: (state, action) => {
state.data.push(action.payload);
}
}
});

useReducer + Typescript on a async maner

I'm having an issue with useReducer + Typescript + async. I just can't do it! When I call anything from async function it return a Promise which break my code. When I tried to get it other way, the component is doesn't re-render! That is Driving me crazy.
I wrote this issue on my personal project which represents the problem I have! https://github.com/igormcsouza/full-stack-todo/issues/15
What I can do to make it work?
I want to make a call from the backend populate the list with the information I got from backend. So my frontend need to re-render every time any change is done to the backend (when add, update or delete any registry there).
reducers.tsx
import { delete_todo, fetch_todos, insert_todo, update_todo } from
"../utils";
import { State, Actions, Todo } from "../TodoContext";
export const INITIAL_STATE: State = {
todos: [],
};
export const reducer = (state: State, action: Actions): State => {
let newState: State = {};
switch (action.type) {
case "POPULATE":
fetch_todos().then((value) => (newState = value));
return newState;
case "ADD_TODO":
if (state.todos) {
const newTodo: Todo = {
when: (+new Date()).toString(),
task: action.payload,
checked: false,
by: "Igor Souza",
};
insert_todo(newTodo);
}
fetch_todos().then((value) => (newState = value));
return newState;
case "CHECK_TODO":
action.payload.checked = !action.payload.checked;
update_todo(action.payload);
fetch_todos().then((value) => (newState = value));
return newState;
case "EDIT_TODO":
let todo = action.payload.task;
todo.task = action.payload.newTaskName;
update_todo(todo);
fetch_todos().then((value) => (newState = value));
return newState;
case "DELETE_TODO":
delete_todo(action.payload);
fetch_todos().then((value) => (newState = value));
return newState;
default:
return state;
}
};
utils.tsx (with the axios calls)
import axios from "axios";
import { State, Todo } from "./TodoContext";
// const base = "http://backend:2500";
const base = "https://full-stack-todo-bknd.herokuapp.com";
export async function fetch_todos(): Promise<State> {
let todos: State = {};
await axios
.get<State>(base + "/api/todo")
.then((response) => {
const { data } = response;
todos = data;
})
.catch((e) => console.log(e));
console.log(typeof todos.todos);
return todos;
}
export async function insert_todo(todo: Todo) {
await axios.post(base + "/api/todo", todo).catch((e) => console.log(e));
}
export async function update_todo(todo: Todo) {
await axios.put(base + "/api/todo/" + todo.id).catch((e) => console.log(e));
}
export async function delete_todo(todo: Todo) {
await axios
.delete(base + "/api/todo/" + todo.id)
.catch((e) => console.log(e));
}
context.tsx (Context APi)
import React, { createContext, useReducer } from "react";
import { reducer, INITIAL_STATE } from "./reducers";
type ContextProps = {
state: State;
dispatch: (actions: Actions) => void;
};
export interface Todo {
id?: string;
task: string;
when: string;
checked: boolean;
by: string;
}
export interface State {
todos?: Array<Todo>;
}
export interface Actions {
type: string;
payload?: any;
}
export const TodoContext = createContext<Partial<ContextProps>>({});
const TodoContextProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
return (
<TodoContext.Provider value={{ state, dispatch }}>
{children}
</TodoContext.Provider>
);
};
export default TodoContextProvider;
Put simply, what you are trying to do is not possible. You cannot have a reducer that is asynchronous. This means that you need to move the async logic outside of the reducer itself.
The reducer is just responsible for applying the data from the action to the state. Since you are re-fetching the whole list after every action (not ideal) you only have one real action which is to replace the whole state. You would do the aysnc fetching and then refresh the state.
export const populate = (dispatch: Dispatch<Actions>) => {
fetch_todos().then((data) =>
dispatch({
type: "POPULATE",
payload: data
})
);
};
export const reducer = (state: State, action: Actions): State => {
switch (action.type) {
case "POPULATE":
return action.payload;
...
<button onClick={() => populate(dispatch)}>Populate</button>
Passing the dispatch function to an action creator is called a "thunk" and it's a popular pattern with Redux. We don't have any middleware, so we just directly call populate(dispatch) instead of something like dispatch(populate()).
Look for ways that you can streamline your code.
We can make use of the fact that all our actions call the same fetch_todos() in order to simplify things (for now -- eventually you want to not refresh the entire list after every change).
insert_todo, update_todo, and delete_todo are all extremely similar. The main difference is the axios method which can be passed as an argument with axios.request.
Though the more I look, the more I see that they should be less similar! You need to pass the todo data on your put request. You want the id property on Todo to be required and for add_todo to take Omit<Todo, 'id'>.
The inverted approach would be to make changes directly to the reducer state first. Then use a useEffect to detect changes and push the to the backend.

Redux - dispatch is not being called

I'm wrapping my head around this and cannot figure out why it's not working.
I have a simple action:
export const GET_EXPENSE_LIST = "GET_EXPENSE_LIST"
export const getExpenseList = () => {
return async dispatch => {
console.log('Action called')
dispatch({ type: GET_EXPENSE_LIST, expenseList: []})
}
}
And a reducer:
import { GET_EXPENSE_LIST } from "../actions/expenses"
const initialState = {
expenseList = []
}
export default (state = initialState, action) => {
console.log("reducer called")
}
I'm calling the action from a component like so (if it matters):
useEffect(() => {
dispatch(expensesActions.getExpenseList())
}, [dispatch]);
In my console I do see the "action called" but I don't see the "reducer called". Why the reducer is not being called?
Did you add thunk middleware to the config of redux? In you action you use redux-thunk

Resources