useSelector not updating with Redux Toolkit - reactjs

I've been battling this all day long and I'd appreciate any help.
I have a redux store built with Redux Toolkit and createSlice that looks like so:
const initialState = {
analiticaNumber: "",
animal: {},
tests: [{ key: "G9116", value: "DERMATOFITOS PCR/ MUESTRA" }],
};
const PeticionSlice = createSlice({
name: "peticion",
initialState,
reducers: {
addTest: (state, action) => {
state.tests.push(action.payload);
},
},
});
export const { addTest: addTestActionCreator } = PeticionSlice.actions;
export const testsArray = (state) => state.Peticion.tests;
export default PeticionSlice.reducer;
I also have a root reducer that imports the rest of the slices and names them as such
import { combineReducers } from "redux";
import NavigationSlice from "./NavigationSlice";
const RootReducer = combineReducers({
Peticion: PeticionSlice,
});
export default RootReducer;
When I add tests to the tests array it works fine and shows in the redux devtools.
The promblem comes that react does not see the change in the store and won't update the child component:
import { testsArray } from "./Store/PeticionSlice";
That's how I import namely the testsArray to call with the useSelector.
The tradicional way of const { tests } = useSelector( (state) => state.Peticion) doesn't work either.
function App() {
const tests = useSelector(testsArray);
useEffect(() => {
console.log("tests");
}, [tests]);
return (
<StylesProvider injectFirst>
<div className="App">
<nav>
<Navbar />
</nav>
{tests.map((test) => (
<p>{test.key}</p>
))}
</div>
</StylesProvider>
);
}
I belive it has to do something with the mutability of the state, but I thought the toolkit took care of that, and for the life of me I don't know how to solve this.
Any help??? Thanks a lot.
** UPDATE **
I believe it has to do with the way I dispatch the actions. Because I needed to add several boundaries to what the app does, I decided to have an external function that filters and dispatches accordingly. It is not a react component.
import { configureStore } from "#reduxjs/toolkit";
import { addTestToList, addTestActionCreator } from "../Store/PeticionSlice";
import RootReducer from "../Store/RootReuder";
const PruebasToSubmitArray = [];
const store = configureStore({
reducer: RootReducer,
});
const handleTestList = (test, action) => {
const anatomia = "A";
const microbiologia = "M";
function oneBiopsia() {
while (test.key.toString().charAt(0) === anatomia) {
return PruebasToSubmitArray.some(
(pruebaInArray) => pruebaInArray.key.toString().charAt(0) === anatomia
);
}
return false;
}
if (!oneBiopsia() && action === "add") {
switch (test.key.toString().charAt(0)) {
case anatomia:
// console.log("Open pdf for anatomia");
store.dispatch(addTestActionCreator(test));
break;
case microbiologia:
// console.log("Open pdf for micro");
store.dispatch(addTestActionCreator(test));
break;
default:
// console.log("add test to the list, ", test);
store.dispatch(addTestActionCreator(test));
break;
}
} else if (action === "remove") {
// console.log("remove test from the list, ", test);
} else if (oneBiopsia()) {
console.log("Only one biopsia per peticion, ", newState);
}
return null;
};
export default handleTestList;
I added a button on App component and it worked as expected (i showed the updated state), as is right now redux updates the state but the component won't reflect it.
Code SandBox as complete as I can

Very odd behavior in my case.
I did
state = action.payload
and that didn't work.
Once I switched to
state.viewer = action.payload.viewer
everything worked!

Multiple Instances of Store
You create a store variable in your index.js file and pass that store to the react-redux Provider component. This is the store instance which all react-redux useSelector and useDispatch hooks will interact with.
In your HandleTestList.js file you create a different store variable. You then dispatch actions to that store, but those actions won't be reflected in your React app because this isn't the store that your React app uses.
handleTestList needs to either A) import the same global store variable. You will want to move this out of index.js and into store.js to avoid circular dependencies. or B) accept dispatch as an argument.

Related

Redux useSelector returns nothing in child component

I am new to React Native and Redux, and was hoping someone could help out in my issue? I have a parent component that fetches some user data (their location) and dispatches to a redux store:
Parent
import { useDispatch } from 'react-redux'
import { setLocation } from './store/locationSlice'
const App = () => {
const dispatch = useDispatch()
const getLocation = () => {
const location = await fetchLoc()
dispatch(setLocation(location))
}
useEffect(() => {
getLocation()
},[])
}
My child component is intended to retrieve this data using the useSelector hook
Child
import { useSelector } from 'react-redux'
const HomeScreen = () => {
const location = useSelector(state => state.location)
useEffect(() => {
if (location) {
getEntitiesBasedOnLocation(location)
}
},[location])
}
However, in my case, useSelector never retrieves the up-to-date information that i have dispatched in the parent, with location returning undefined. I'm fairly certain there's a simple oversight here, but i'm at a loss as to what this could be. I was under the impression that useSelector subscribes to state changes, so why is it that that my dispatched action that causes a change of state is ignored? Using my debugger, I can see that my state is definitely updated with the correct data, but the child component doesn't pick this up..
Here's my location slice:
import { createSlice } from '#reduxjs/toolkit'
const initialState = {
location: {
id: null,
name: null,
latitude: null,
longitude: null
}
}
const locationSlice = createSlice({
name: 'location',
initialState,
reducers: {
setLocation: (state, action) => {
const { id, name, latitude, longitude } = action.payload
state.location = { id, name, latitude, longitude }
}
}
})
export const { setLocation } = locationSlice.actions
export default locationSlice.reducer
UPDATE
The store is configured by wrapping the App.js component in a Provider component, with the store passed as its props as follows:
Root.js
import { configureStore } from '#reduxjs/toolkit'
import { Provider } from 'react-redux'
import locationReducer from './src/store/locationSlice'
import App from './src/App'
const Root = () => {
const store = configureStore({ reducer: locationReducer })
return (
<Provider store={store)>
<App />
</Provider>
)
}
The issue is in your selector. You've created the slice called 'location' and within that slice you've got your state { location: {...}}. So from the perspective of the selector (which accesses your global state, not just the location slice) the path to your data would be state.location.location. But your selector is trying to read out of state.location which only has a location prop. Anything else you tried to read out would be undefined.
It is common to export a custom selection function from the slice configuration. Remember that the selector must take exactly the data that you want to share in your component tree (locationSlice.state.location in this case). This is not mandatory, it is just to facilitate development.
// locationSlice
import { createSlice } from '#reduxjs/toolkit'
//...
export const { setLocation } = locationSlice.actions
export const selectLocation = (state) => state.location.location
export default locationSlice.reducer
// Child
import { useSelector } from 'react-redux'
import {selectLocation} from './src/store/locationSlice'
const HomeScreen = () => {
const location = useSelector(selectLocation)
//...
}
My workaround was to move my getLocation() function in the parent to the child component. useSelector now gets the state as expected. I feel that this work-around defeats the object of having global state access though, and i could probably just use local state rather than Redux.

How to save the result of my API call to my redux store, and call my API when my component firsts loads?

So I created a react redux toolkit app and I am trying to play with the redux and actions.
I have a simple react component that looks like this:
import React, { useState } from 'react';
import { useAppSelector, useAppDispatch } from '../../app/hooks';
import {
setBoard,
fetchBoardAsync,
selectBoard
} from './boardSlice';
import styles from './Board.module.css';
export function Board() {
const board = useAppSelector(selectBoard);
const dispatch = useAppDispatch();
console.log(JSON.stringify(board));
return (
<div>
<div className={styles.row}>
<h3>Board</h3>
<button
className={styles.asyncButton}
onClick={() => dispatch(fetchBoardAsync(""))}
>
Fetch board Data from API
</button>
</div>
</div>
);
}
When I click the button, it fetches some JSON - but right now it is just hard coded json variable.
// A mock function to mimic making an async request for data
export function fetchBoard() {
return new Promise<{ data: any }>((resolve) =>
setTimeout(() => resolve({ data: boardJson} ), 50)
);
}
where boardJson is simply:
let boardJson = { .... }
My boardSlice looks like:
import { createAsyncThunk, createSlice, PayloadAction } from '#reduxjs/toolkit';
import { RootState, AppThunk } from '../../app/store';
import { fetchBoard } from './boardAPI';
export interface BoardState {
board: any;
status: 'idle' | 'loading' | 'failed';
}
const initialState: BoardState = {
board: {},
status: 'idle',
};
export const fetchBoardAsync = createAsyncThunk(
'board/fetchBoard',
async (boardId: string) => {
const response = await fetchBoard();
console.log('fetch board returned data...' + JSON.stringify(response.data));
return response.data;
}
);
export const boardSlice = createSlice({
name: 'board',
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
setBoard: (state, action: PayloadAction<any>) => {
state.board = action.payload;
}
},
I have 2 questions.
#1
When I click the button and it fetches the board, how do I save the result to my redux state?
#2
Also, in my Board component, how can I run fetchBoard when the component loads instead of having to click a button to trigger it? (this used to be a component lifecycle event like componentDidMount I think)
When I click the button and it fetches the board, how do I save the result to my redux state?
Your boardSlice reducer almost does what you expect. In the reducers field, you have provided an object of key/reducer values. Redux is unable to associate the key setBoard with the action created by fetchBoardAsync. If you were to dispatch({ type: 'setBoard', payload }) then you would see your reducer fire as expected. Notice how the type is identical to the reducer key.
createAsyncThunk example from Redux documentation
Matching utilities in RTK
Instead, you can use RTK builder syntax and matchers for the desired result:
export const boardSlice = createSlice({
name: 'board',
initialState,
extraReducers(builder) {
builder.addCase(fetchBoardAsync.fulfilled, (state, action) => {
state.board = action.payload;
})
},
};
#2 Also, in my Board component, how can I run fetchBoard when the component loads instead of having to click a button to trigger it? (this used to be a component lifecycle event like componentDidMount I think)
In a functional component, most React developers use the React hook useEffect for managing side-effects in a similar fashion to componentDidMount/componentWillMount and componentWillUnmount. The documentation provides a lot of clarity on all the ways developers can leverage this hook.
For example:
import React, { useEffect, useState } from 'react';
import { useAppSelector, useAppDispatch } from '../../app/hooks';
import {
setBoard,
fetchBoardAsync,
selectBoard
} from './boardSlice';
import styles from './Board.module.css';
export function Board() {
const board = useAppSelector(selectBoard);
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(fetchBoardAsync(""))
}, []); // an empty dependency array tells React to only run the effect after mount
console.log(JSON.stringify(board)); // may not have loaded yet
return (
<div>
{/* snip */}
</div>
);
}
Once dispatched, thunks receive a second parameter for additional Redux functionality. A traditional thunk, which is the result of dispatching a function, receives redux API with this signature:
function fetchBoardAsync() {
return (dispatch, getState) => {
// now you can dispatch even more actions!
// I don't believe this is necessary for your current use-case, but this is helpful for complicated side-effects in many apps
}
}
Redux thunk documentation
When using createAsyncThunk, the signature is this:
function fetchBoardAsync(arg, api) {
const { dispatch, extra, fulfillWithValue, getState, rejectWithValue, requestId, signal } = api;
}
createAsyncThunk signature
Remember, you must still dispatch the thunk (either a function or the return value of createAsyncThunk) itself before you can use dispatch inside the thunk callback.

React-Redux - How to redirect the page after storing the data in redux store?

I am trying out a react-redux sample code where I would like to add a course in one form upon clicking 'Add Course', I want to update the store and redirect to a new page with the list of courses.
But for some reason, the redirect happen after calling the redux action creator. It stays in the same page.
Any ideas how to redirect the results to a different page?
import React from "react";
import { connect } from "react-redux";
import * as courseActions from "../../redux/actions/courseActions";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import history from './history'
class CoursesPage extends React.Component {
state = {
course: {
title: "",
},
};
handleSubmit = (event) => {
event.preventDefault();
this.props.actions.loadCourses.createCourse(this.state.course).then(() => {
alert('Inside Promise')
history.push('/AllCourses'); //This doesn't get executed.
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<h2>Courses</h2>
<h3>Add Course</h3>
<input type="submit" value="Add Course" />
{this.props.courses.map((course) => (
<div key={course.title}>{course.title}</div>
))}
</form>
<hr />
</div>
);
}
}
CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return {
courses: state.courses,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
loadCourses: bindActionCreators(courseActions, dispatch),
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
Action Code:
import * as types from "./actionTypes";
export function createCourse(course) {
return { type: types.CREATE_COURSE, course };
}
Reducer:
import * as types from "../actions/actionTypes";
export default function courseReducer(state = [], action) {
debugger;
switch (action.type) {
case types.CREATE_COURSE:
return [...state, { ...action.course }];
default:
return state;
}
}
history.js
import createHistory from 'history/createHashHistory'
export default createHistory()
You can create a custom middleware to do so:
const hasAddedData = (state) => {
// Your checks
}
const redirectMiddleware = history => storeAPI => next => action => {
console.log('dispatching', action)
const result = next(action);
// If the action is the one you want to trigger the redirect (action.type)
// and the state pass the checks (storeAPI.getState()),
// do the redirect.
//
// This would be like:
if (action.type === types.CREATE_COURSE && hasAddedData(storeAPI.getState())) {
history.push(destinationPath);
}
// You must return the result of next(action) to avoid breaking Redux.
return result;
}
And wherever you create your Redux Store:
// history should already be provided by React Router.
const middlewareEnhancer = applyMiddleware(redirectMiddleware(history))
const store = createStore(yourRootReducer, middlewareEnhancer)
If you need to check the previous state too, just set a const with storeAPI.getState() before running next(action). You can expand your middleware with other redirect checks or scenarios you need for additional actions.
WARNING: I wanted to give you the vanilla code solution, but keep in mind these three things:
This is a task that is probably better and opinionatedly made by a library (check connected-react-router).
Also, instead of making a custom middleware for action specific tasks, you can use a widely accepted middleware library such as redux-saga.
Think about your app workflow. Do you need additional state properties (done flags, selection properties...)? Are all the CREATE_COURSE actions going to redirect or only a fraction of them? Will a specific REDIRECT action make things easier for you? Do you really need an imperative redirect or would it be possible, with the right state structure, a declararive Redirect with React Router component?

How to access the Redux store outside of a component in React

I am beginning with Redux and I always used it in components with connect() and mapStateToProps(), but now I want to call my API with setInterval() every x time to check if the server has new data not stored in the Redux store, and substitute it.
My approach was to create a function that reads the store and update it like that:
import { store } from './dir/dir/store.js'
const refresher = async () => {
const state = store.getState();
// Call API, compare 'state.calendar' with calendar from server
// Call store.dispatch() if they are different, then update Redux store
}
export default refresher
My questions are:
Is this a good practise to use Redux?
Is there a better approach to this problem?
Thanks
It's perfectly fine to export the store and use within a vanilla js/ts file.
Example Redux Store
Make sure to export the store that you create
import { configureStore } from "#reduxjs/toolkit";
import { slice } from "../features/counterSlice";
export const store = configureStore({
reducer: {
counter: slice.reducer
}
});
Usage in Non-Component Code:
You can then import the created store in any other code
import { store } from "../App/store";
import { slice as counterSlice } from "../features/counterSlice";
export function getCount(): number {
const state = store.getState();
return state.counter.value;
}
export function incrementCount() {
store.dispatch(counterSlice.actions.increment());
}
Traditional Usage in Functional Component
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../App/store";
import { slice as counterSlice } from "../features/counterSlice";
export function Clicker() {
const dispatch = useDispatch();
const count = useSelector((state: RootState) => state.counter.value);
const dispatchIncrement = () => dispatch(counterSlice.actions.increment())
// ...
Example Slice
import { createSlice } from "#reduxjs/toolkit";
export const slice = createSlice({
name: "counter",
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
}
}
});
Demo in Codesandbox
Note: You cannot use this option with Server Side Rendering. If you need to support SSR, you can use middleware to listen to dispatched actions and handle elsewhere.
Further Reading
What is the best way to access redux store outside a react component? | Stack Overflow
Access the Redux Store Outside a React Component | Blog
How can I access the store in non react components? | Github Issues
Here you can access the store and action out side any component like index.js file in react-native.
import {updateLocationAlertItem} from './src/store/actions/locationAlertAction';
import {store} from './src/store/index';
store.subscribe(listener);
function listener() {
state = store.getState().locationAlertReducer;
}
store.dispatch(
updateLocationAlertItem({
index: index,
is_in_radius: true,
is_notification: true,
arrival_time: moment().format('DD/MM/YYYY hh:mm'),
exit_time: item.exit_time,
}),
);

Empty Redux store when attempting to dispatch from outside React component

I have what I think is a fairly standard React-Redux setup with some persistence mixed in.
app.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import AppRouter from './routers/AppRouter';
import configureStore from './store/configureStore';
import config from 'cgConfig';
const { store, persistor } = configureStore();
const jsx = (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<AppRouter />
</PersistGate>
</Provider>
);
ReactDOM.render(jsx, document.getElementById(config.constants.element.rootId));
configureStore.js
import {
createStore,
combineReducers
} from 'redux';
import {
persistStore,
persistReducer
} from 'redux-persist';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import storage from 'redux-persist/lib/storage';
import config from 'cgConfig';
//...import reducers...
export default () => {
const persistConfig = {
key: 'root',
storage,
stateReconciler: autoMergeLevel2
};
let rootReducer = combineReducers({
//...all of my reducers...
});
let store = undefined;
let pr = persistReducer(persistConfig, rootReducer);
if (config.env.includeReduxDevTools) {
store = createStore(
pr,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
} else {
store = createStore(pr);
}
let persistor = persistStore(store);
return {
store,
persistor
};
};
However, the one thing that is a bit unconventional is that I need to update the store outside the context of a react component. As far as I understand (for example), this should not be too difficult to accomplish. Simply call configureStore() to get the store and run a store.dispatch(action). Problem is that I keep getting the initial state of the store back (IE empty), which isn't the same as the one I have already set up through the process of logging in etc. Thus when I run a dispatch, the wrong state is being updated.
Not sure what I am doing wrong, would appreciate any help.
EDIT to answer Uma's question about what the router looks like:
First some more context. The website I am working on will basically have shapes generated in something akin to a graph. These shapes can be manipulated after they are selected from various sources like contextual menus and a toolbar. It is in the context of this change event that I am working on.
When a change is made, the info of the selected item and what needs to be changed will be sent to a generic function which will determine which reducer/action to use to update the Redux store. All my reducers follow the same pattern and look like this:
const reducerInitialState = {};
const setSomeProperty= (state, action) => {
let newState = { ...state };
newState.some_property = action.some_update;
return newState;
};
export default (state = reducerInitialState, action) => {
switch (action.type) {
case 'UPDATE_SOME_PROPERTY':
return setSomeProperty(state, action);
case 'LOG_OUT':
return { ...reducerInitialState };
default:
return state;
}
};
Action for completeness:
export const setSomeProperty = update_data => ({
type: 'UPDATE_SOME_PROPERTY',
some_update: update_data
});
The generic function I have would look something like this:
import configureStore from './store/configureStore';
import { setSomeProperty} from './actions/SomeAction';
import API from './utilities/API';
export default async ({ newValue, selectedShape }) => {
if (!newValue || !selectedShape)
throw "Cannot update the server with missing parameters.";
await API()
.post(
`/api/update-shape`,
{
newValue,
shape: selectedShape
}
)
.then(response => {
updateValue({ selectedShape, newValue });
})
.catch(error => {
// handle error
});
}
const getAction = ({ shape }) => {
switch (shape.type) {
case 0:
return setSomeProperty;
default:
throw `Invalid type of ${shape.type} attempting to update.`;
}
}
const updateValue = ({ selectedShape, newValue }) => {
const action = getAction({ shape: selectedShape })
const { store } = configureStore();
store.dispatch(action(newValue))
}
Note: API is a wrapper for Axios.
Since posting this yesterday I have read that creating a second store like what I am doing with const { store } = configureStore(); is where one of my problems lie in that React/Redux can't have 2 of them. I have also come to realize that the problem most likely have to do with the initial state in my reducers, that somehow using configureStore() does not send the actual state to the reducers and thus all my reducers are showing their initial states when I look at them using console.log(store.getState());. If this is true, at least I know the problem and that is half the battle, but I am unsure how to proceed as I have tried to ReHydrate the state I get from configureStore() but nothing seems to work the way I expect it to.
As far as I can tell you end up in a weird loop where you call an action setSomeProperty then it gets you to the reducer, and in reducer you call that setSomeProperty action again.
In reducer I would expect to see something like this:
export default (state = reducerInitialState, action) => {
switch (action.type) {
case 'UPDATE_SOME_PROPERTY':
return {
...state, // preserve already set state properties if needed
some_update: action.some_update
}
case 'LOG_OUT':
return { ...reducerInitialState };
default:
return state;
}
};

Resources