I'm learning Redux-Saga and everything works well with { configureStore, getDefaultMiddleware, createAction, createReducer }. However, I cannot successfully implement createSlice.
My actions seem to be dispatched just fine (though I'm not sure since I have multiple Redux stores and placing console.log inside createSlice doesn't seem to work...). I just cannot get the store values - after dispatched action the relevant state value (initially '') becomes undefined. I did wrap my component inside Provider and all. Can someone enlighten me how does createSlice work? Thanks.
RESOLVED I had a bug somewhere else in my code, that's why the reducers weren't working proberly. BUT what I was asking about and what was causing my problems is this: actions passed to createSlice must be 'pure' functions, meaning: (state, action) -> state, nothing fancy. That's why I had to remove my fetching functions (getData1 and getData2) from this createSlice.
ComponentWrapper returns this
<Provider store={toolkitCreateSliceStore}>
<ReduxToolkitCreateSliceComponent />
</Provider>
Component (Buttons just dispatch actions)
class ReduxToolkitCreateSliceComponent extends React.Component {
render () {
return (
<>
<h2>
{this.props.data1}
{(this.props.data1!=='' && this.props.data2!=='') ? ', ' : ''}
{this.props.data2}
</h2><br/>
<h3>{this.props.message}</h3>
<Button1 />
<Button2 />
<Button3 />
</>
);
}
}
function mapStateToProps(state) {
return {
data1: state.toolkitCreateSliceReducer.data1,
data2: state.toolkitCreateSliceReducer.data2,
message: state.toolkitCreateSliceReducer.message
};
}
export default connect(mapStateToProps)(ReduxToolkitCreateSliceComponent);
Redux Toolkit slice
import { createSlice } from "#reduxjs/toolkit";
import axios from "axios";
const initialSliceState = {
data1: '',
data2: '',
message: ''
};
const slice = createSlice({
name: "slice",
initialState: initialSliceState,
reducers: {
getData1: (state, action) => {
return dispatch => {
dispatch(loading1());
return axios.get('http://localhost:8081/data1')
.then(function (response) {
if (response.status === 200) {
dispatch(setResponse1(response.data));
}
}).catch(error => dispatch(displayError1(error)));
};
},
getData2: (state, action) => {
return dispatch => {
dispatch(loading2());
return axios.get('http://localhost:8081/data2')
.then(function (response) {
if (response.status === 200) {
dispatch(setResponse2(response.data));
}
}).catch(error => dispatch(displayError2(error)));
};
},
setResponse1: (state, action) => {
state.data1 = action.payload;
state.message = 'success';
},
setResponse2: (state, action) => {
state.data2 = action.payload;
state.message = 'success';
},
reset: (state, action) => {
state.data1 = '';
state.data2 = '';
state.message = 'reset';
},
loading1: (state, action) => {
state.message = 'loading';
},
loading2: (state, action) => {
state.message = 'loading';
},
displayError1: (state, action) => {
state.message = action.payload;;
},
displayError2: (state, action) => {
state.message = action.payload;;
}
}
});
export const toolkitCreateSliceReducer = slice.reducer;
const { getData1, getData2, setResponse1, setResponse2, reset, loading1, loading2,
displayError1, displayError2} = slice.actions;
export default slice;
Redux Toolkit store
const middleware = [
...getDefaultMiddleware()
];
const toolkitCreateSliceStore = configureStore({
reducer: {
toolkitCreateSliceReducer
},
middleware
});
export default toolkitCreateSliceStore;
Your "reducers" are very wrong.
A reducer must never have any side effects like AJAX calls.
You've written some Redux "thunk" functions where your reducers should be:
getData1: (state, action) => {
return dispatch => {
dispatch(loading1());
return axios.get('http://localhost:8081/data1')
.then(function (response) {
if (response.status === 200) {
dispatch(setResponse1(response.data));
}
}).catch(error => dispatch(displayError1(error)));
};
},
This is a thunk, not a reducer.
A reducer would be something like:
getData(state, action) {
return action.payload;
}
I'd specifically recommend reading through our brand-new "Redux Essentials" core docs tutorial, which teaches beginners "how to use Redux, the right way", using our latest recommended tools and practices like Redux Toolkit. It specifically covers how reducers should work, how to write reducers with createSlice, and how to write and use thunks alongside createSlice:
https://redux.js.org/tutorials/essentials/part-1-overview-concepts
If you're interested in creating async actions, let me recommend you an npm package that I created and use. It is saga-toolkit that allows async functions to get resolved by sagas.
slice.js
import { createSlice } from '#reduxjs/toolkit'
import { createSagaAction } from 'saga-toolkit'
const name = 'example'
const initialState = {
result: null,
loading: false,
error: null,
}
export const fetchThings = createSagaAction(`${name}/fetchThings`)
const slice = createSlice({
name,
initialState,
extraReducers: {
[fetchThings.pending]: () => ({
loading: true,
}),
[fetchThings.fulfilled]: ({ payload }) => ({
result: payload,
loading: false,
}),
[fetchThings.rejected]: ({ error }) => ({
error,
loading: false,
}),
},
})
export default slice.reducer
sagas.js
import { call } from 'redux-saga/effects'
import { takeLatestAsync } from 'saga-toolkit'
import API from 'hyper-super-api'
import * as actions from './slice'
function* fetchThings() {
const result = yield call(() => API.get('/things'))
return result
}
export default [
takeLatestAsync(actions.fetchThings.type, fetchThings),
]
Related
I have this redux slice setup in store/slices/sourcesSlice.ts
import { addInitialSources} from "store/slices/sourcesActions.ts";
export const sourcesSlice = createSlice({
name: "sourcesSlice",
initialState,
reducers: {
addSource: (state, action: PayloadAction<SourceInterface>) => {
state.sources.push(action.payload);
},
changeName: (state) => {
state.naming = "Bob Marley";
},
},
extraReducers: (builder) => {
builder
.addCase(addInitialSources.fulfilled, (state, { payload }) => {
state.loading = false;
state.sources = payload;
})
},
});
export const { addSource, changeName } = sourcesSlice.actions;
Note how I have a number of actions in store/slices/sourcesSlice.ts and a number of actions in store/slices/sourcesActions.ts
All addSource, changeName, addInitialSources are related actions. **Shouldn't they all be accessible from one endpoint? So when I import any of those, I think it's cleaner, easier to remember if I can do this
import { addInitialSources, addSource, changeName} from "store/slices/sourcesActions.ts";
Rather than this
import { addInitialSources} from "store/slices/sourcesActions.ts";
import { addSource, changeName} from "store/slices/sourcesSlice.ts";
Is such a thing possible? To leave export const sourcesSlice = createSlice... in sourcesSlice.ts but to call all the actions from sourcesActions.ts
AND IS IT RECOMMENDED
I have the following initialState For React Redux:
const inistialStateRedux = {
configuredFilters: {
data: {
countries: [],
divisions: [],
companies: [],
locations: [],
fields: [],
search: '',
},
},
};
Now I want to create a RESET reducer.
It looks like that:
export const createReducer = (initialState, handlers) => (
state = initialState,
action
) => {
if (action.type in handlers) {
return handlers[action.type](state, action);
}
return state;
};
export const multiUse = (reducer, name = '') => (state = null, action) => {
if (action.name !== name) return state;
return reducer(state, action);
};
import {
createReducer
} from '../helper';
import * as Action from './actions';
import inistialStateRedux from '../inistialStateRedux';
export default createReducer({
data: {},
}, {
[Action.RESET_CONFIGURED_FILTERS]: (state) => ({
...state,
data: {
...inistialStateRedux.configuredFilters.data,
},
}),
});
But Redux Devtools shows, that the states are equal. What am I doing wrong ?
In the Actions you can use a dispatcher to reset the Form.
Like this:
import axios from 'axios';
import { ADD} from '../modelType';
import { reset } from 'redux-form';
export const add= formValues => async dispatch => {
const res = await axios.post('/api/model/', { ...formValues });
dispatch({
type: ADD,
payload: res.data
});
dispatch(reset('yourUniqueFormName'));
};
I'm using Redux Toolkit to connect to an API with Axios.
I'm using the following code:
const products = createSlice({
name: "products",
initialState: {
products[]
},
reducers: {
reducer2: state => {
axios
.get('myurl')
.then(response => {
//console.log(response.data.products);
state.products.concat(response.data.products);
})
}
}
});
axios is connecting to the API because the commented line to print to the console is showing me the data. However, the state.products.concat(response.data.products); is throwing the following error:
TypeError: Cannot perform 'get' on a proxy that has been revoked
Is there any way to fix this problem?
I would prefer to use createAsyncThunk for API Data with extraReducers
Let assume this page name is productSlice.js
import { createSlice,createSelector,PayloadAction,createAsyncThunk,} from "#reduxjs/toolkit";
export const fetchProducts = createAsyncThunk(
"products/fetchProducts", async (_, thunkAPI) => {
try {
//const response = await fetch(`url`); //where you want to fetch data
//Your Axios code part.
const response = await axios.get(`url`);//where you want to fetch data
return await response.json();
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message });
}
});
const productsSlice = createSlice({
name: "products",
initialState: {
products: [],
loading: "idle",
error: "",
},
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchProducts.pending, (state) => {
state. products = [];
state.loading = "loading";
});
builder.addCase(
fetchProducts.fulfilled, (state, { payload }) => {
state. products = payload;
state.loading = "loaded";
});
builder.addCase(
fetchProducts.rejected,(state, action) => {
state.loading = "error";
state.error = action.error.message;
});
}
});
export const selectProducts = createSelector(
(state) => ({
products: state.products,
loading: state.products.loading,
}), (state) => state
);
export default productsSlice;
In your store.js add productsSlice: productsSlice.reducer in out store reducer.
Then for using in component add those code ... I'm also prefer to use hook
import { useSelector, useDispatch } from "react-redux";
import {
fetchProducts,
selectProducts,
} from "path/productSlice.js";
Then Last part calling those method inside your competent like this
const dispatch = useDispatch();
const { products } = useSelector(selectProducts);
React.useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
And Finally, you can access data as products in your component.
It is happening because your reducer function is not a pure function, it should not be having any asynchronous calls.
something like this should work. it will fix the error you are getting
const products = createSlice({
name: "products",
initialState: {
products: []
},
reducers: {
reducer2: (state, { payload }) => {
return { products: [...state.products, ...payload]}
})
}
}
});
and api should be called outside
const fetchProducts = () => {
axios.get('myurl')
.then(response => {
//console.log(response.data.products);
store.dispatch(products.actions.reducer2(response.data.products))
})
};
PS: haven't tried running above code, you may have to make modifications as per your need.
I need to reset current state to initial state. But
all my attempts were unsuccessful. How can I do it using redux-toolkit?
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState: {
returned: [],
},
reducers: {
reset(state) {
//here I need to reset state of current slice
},
},
});
Something like this:
const intialState = {
returned: []
}
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState,
reducers: {
reset: () => initialState
}
});
This worked for me (mid-late 2020). Formatted with your code context as an example.
const initialState = {
returned: [],
};
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState,
reducers: {
reset: () => initialState,
},
});
Replacing state with initialState directly did not work for me (mid 2020). What I finally got working was to copy each property over with Object.assign(). This worked:
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState: {
returned: []
},
reducers: {
reset(state) {
Object.assign(state, initialState)
}
}
});
When using multiple slices, all slices can be reverted to their initial state using extraReducers.
First, create an action that can be used by all slices:
export const revertAll = createAction('REVERT_ALL')
In every slice add an initialState, and an extraReducers reducer using the revertAll action:
const initialState = {};
export const someSlice = createSlice({
name: 'something',
initialState,
extraReducers: (builder) => builder.addCase(revertAll, () => initialState),
reducers: {}
});
The store can be created as usual:
export const store = configureStore({
reducer: {
someReducer: someSlice.reducer,
}
})
And in your react code you can call the revertAll action with the useDispatch hook:
export function SomeComponent() {
const dispatch = useDispatch();
return <span onClick={() => dispatch(revertAll())}>Reset</span>
}
In my case, as the previous answer, mid 2021, just setting the initial state DO NOT WORK, even if you use the toolkit adapter like :
reducers: {
// Other reducers
state = tasksAdapter.getInitialState({
status: 'idle',
error: null,
current: null
})
}
},
instead, you should use Object.assign(), guess that it's related with the internal immer library behavior
We do it like this guys.
Suppose you want to clear all the data at the point of logging out.
In your store.tsx file:
import { AnyAction, combineReducers, configureStore } from '#reduxjs/toolkit';
import authReducer from './slices/authSlice'
import messageReducer from './slices/messageSlice'
const appReducer = combineReducers({
auth: authReducer,
message: messageReducer,
});
const reducerProxy = (state: any, action: AnyAction) => {
if(action.type === 'logout/LOGOUT') {
return appReducer(undefined, action);
}
return appReducer(state, action);
}
export const store = configureStore({
reducer: reducerProxy,
});
Then you create a thunk like this:
export const logout = createAsyncThunk(
"auth/logout",
async function (_payload, thunkAPI) {
thunkAPI.dispatch({ type: 'logout/LOGOUT' });
console.log('logged out')
}
);
You can use spread opearator for initialState
const initialState: {
returned: unknown[] //set your type here
} = {
returned: []
}
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState,
reducers: {
reset() {
return {
...initialState
}
}
}
});
Try this. In my case, I wanted to return all slices to initialState when a certain action is dispatched.
First, let's create action:
import { createAction } from '#reduxjs/toolkit';
export const resetPanelsAction = createAction('resetPanelsData');
When creating our store, we save a copy of the initialState in the middleware:
import { Middleware } from '#reduxjs/toolkit';
export const resetDataMiddleware: Middleware =
({ getState }) =>
(next) => {
// "Caching" our initial app state
const initialAppState = getState();
return (action) => {
// Let's add the condition that if the action is of
// type resetData, then add our cached state to its payload
if (action.type === 'resetData') {
const actionWithInitialAppState = {
...action,
payload: initialAppState,
};
return next(actionWithInitialAppState);
}
return next(action);
};
};
Almost done! Now let's change our root reducer a little by adding a wrapper that will check the action type, and if it is equal to resetData, then return combinedReducers with our initialState, which will be in payload.
import { AnyAction } from 'redux';
import { combineReducers } from '#reduxjs/toolkit';
export const combinedReducers = combineReducers({
/** Your reducers */
});
export const rootReducer = (
state: ReturnType<typeof combinedReducers> | undefined,
action: AnyAction,
) => {
if (action.type === 'resetPanelsData') {
return combinedReducers(action.payload, action);
}
return combinedReducers(state, action);
};
In my store.js i have the following code:
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk'
const reducer = (state, action) => {
console.log(action.type)
if (action.type === 'LOAD_USERS') {
return {
...state,
users: action.users['users']
}
} else if (action.type === 'LOAD_CHATROOMS') {
return {
...state,
chatRooms: action.chatRooms['chatRooms']
}
}
return state;
}
export default createStore(reducer, {users:[], chatRooms:[]}, applyMiddleware(thunk));
the code inside the action.type === 'LOAD_CHATROOMS' is never accessed for some reason, this is the action file where i set the action type for the reducer:
import axios from 'axios'
axios.defaults.withCredentials = true
const loadUsers = () => {
return dispatch => {
return axios.get('http://localhost:3000/session/new.json')
.then(response => {
dispatch({
type: 'LOAD_USERS',
users: response.data
});
});
};
};
const logIn = user => {
return axios.post('http://localhost:3000/session', {
user_id: user.id
})
.then(response => {
//TODO do something more relevant
console.log('loged in');
});
};
const loadChatRooms = () => {
return dispatch => {
return axios.get('http://localhost:3000/session/new.json')
.then(response => {
dispatch({
type: 'LOAD_CHATROOMS',
chatRooms: response.data
});
});
};
};
const enterChatRoom = chatrom => {
};
export { loadUsers, logIn, enterChatRoom, loadChatRooms};
The 'Load methods' get the data that i use to populate both components (one for users list and the other one for chatrooms list ), both components are called at the same level in the app.js file.
Basically the output that i'm getting is the first component (users) as expected with the correct list, and the chatrooms component is also rendered but the data is not loaded (since it's corresponding reducer block is not accessed).
Thanks a lot for reading :)