React Redux-Persist problem with "cannot read properties of undefined(reading 'subscribe') - javascript

so I'm doing a project where I'm using redux for the first time. I ended up having problem with states becoming undefined when I refresh the browser. To solve this I've tried implementing the redux-persist. But I get errors in my console which I don't know how I should solve. I only use redux for a single thunk-api call, therefor I got all my store code in my index.js file. I have seen all with threads where someone has a similar problem as me, but nothing solved it.
So here's my index.js file:
import React from 'react';
import {createRoot} from 'react-dom/client';
import App from './App';
import {configureStore} from '#reduxjs/toolkit'
import { Provider } from 'react-redux';
import blobReducer from './services/BlobRetriever'
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import { PersistGate } from 'redux-persist/es/integration/react'
const persistConfig = {
key:'persist-key',
storage,
}
const persistedReducer = persistReducer(persistConfig, blobReducer)
const store = configureStore({
reducer: {
blobs: persistedReducer,
},
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
serializableCheck: false,
}),
})
const persistorStore = persistStore(store)
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate loading={null} persistorStore={persistorStore}>
<App />
</PersistGate>
</Provider>
</React.StrictMode>,
);
and here's the error message I got: https://puu.sh/IX9Y2/e441359b38.png
am I doing something wrong?

Related

my redux is not working the way i wrote it down

Lately, I have been trying to use Redux but I get no error and no dev tool error and my page are blank.
So I started my code with the basic Redux boilerplate. I created a userslice, a store and then I provided the store as a wrapper for the <app/>.
Yet after spending hours I can't get to fix the code. Code should just give me back the username inside a div using useselector hook that initialized but it does not seem to work.
App.js:
import React from 'react';
import { useSelector } from 'react-redux';
import './App.css';
function App() {
const username = useSelector(state => state.username)
return (
<div className="App">
{username}
</div>
);
}
export default App;
userSlice.js
import { createSlice } from "#reduxjs/toolkit";
export const userSlice = createSlice({
name:'user'
,
initialState:{
username:'Tony stark',
post:'',
},
reducers:{
updatePost:(state,action)=>{
state.username = action.payload;
}
}})
export const { updatePost} = userSlice.actions;
export default userSlice.reducers;
store.js
import { configureStore } from '#reduxjs/toolkit';
import userSlice from '../redux/userSlice'
export const store = configureStore({
reducer: {
user: userSlice,
},
});
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from '../src/redux/store'
import App from './App';
import './index.css';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
As it's in the userSlice you'll need to get it from the user property of the Redux root state, like so:
const username = useSelector(state => state.user.username)
Your initial Redux state (annotated) should look like this:
{ // <-- state
user: { // <-- state.user
username: 'Tony stark', // <-- state.user.username
post: '' // <-- state.user.post
}
}

Im implementing react redux in my react project. but this error came dont know how?

index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
)
store.js
import { createStore, combineReducers } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { bookReducers } from './reducers/bookReducers'
const reducer = combineReducers({
book: bookReducers,
})
const middleware = [thunk]
const initialState = {
books: [],
isLoading: false,
eror: '',
}
const store = createStore(
reducer,
initialState,
composeWithDevTools(...middleware)
)
export default store
error I got in my console
I got this error from provider component while adding prop store but its the same as in redux docs . what is happening here

store.getState is not a function react-redux

Newbie here in the world of reactjs. I tried using redux and redux thunk along with reducers, though I don't full understand if they are all in one package. I'm creating a login in that will using those items. But I kept on seeing store.getstate is not a function.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {Provider} from 'react-redux';
const store = require('./store/index');
ReactDOM.render(
//<React.StrictMode>
<Provider store="{store()}">
<App />
</Provider>,
//</React.StrictMode>,
document.getElementById('root')
);
store/index.js
import {createStore} from 'redux'
import AllReducers from './reducers/AllReducers';
// import
const initialStates = {
auth: {
loggedIn: false,
user:{}
}
}
const store = createStore(AllReducers,initialStates);
export default store;
store/reducers/AllReducers.js
import { combineReducers } from "redux";
import AuthReducer from "./AuthReducer";
const AllReducers = combineReducers({auth: AuthReducer})
export default AllReducers;
store/reducers/AuthReducers.js
const AuthReducer = (state = {}, actions) => {
switch (actions.type) {
case 'value':
return state;
default:
return state;
}
}
export default AuthReducer;
I kept on getting the TypeError: store.getState is not a function
Can someone help me at least an advice on how to trap this error then i will do the rest for my studying.
Thanks.
I think you did mistake here.
<Provider store="{store()}">
You should write
<Provider store={store}>
I hope this answer will help you!!
The problem in <Provider store="{store()}">. You need to update like this:
<Provider store={store}>

Enabling both redux-promise and redux-saga middlewares appears to cause problems

I'm using an ejected create-react-app codebase and trying to setup both redux-saga and redux-promise middlewares. However redux-saga seems disabled no matter how I approach it or will sometimes report an error indicating that applyMiddleware hasn't been run against the sagaMiddleware object. (Please excuse the slightly convoluted sample code.)
import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import { Route, BrowserRouter, Switch } from 'react-router-dom';
import reducersP1 from './p1/reducers';
import reducersP2 from './p2/reducers';
import Wrapper from './global/containers/wrapper';
import AppWrap from "./p1/components/app_wrap";
import AppWrap2 from "./p2/containers/app_wrap";
import createSagaMiddleware from 'redux-saga';
import rootSaga from './p2/sagas';
const appConfig = {
p1: {
reducers: reducersP1,
component: AppWrap,
namespace: "p1",
api: '/api'
},
p2: {
reducers: reducersP2,
component: AppWrap2,
namespace: "p2",
api: '/api2'
}
};
const { api, reducers, component, namespace } = process.env.REACT_APP_PORTFOLIO==="1"? appConfig.p1: appConfig.p2;
const WrapComponent = component;
export const apiPath = api;
const sagaMiddleware = createSagaMiddleware();
// Approach A.
const createStoreWithMiddleware = applyMiddleware(sagaMiddleware, ReduxPromise)(createStore);
const store = createStoreWithMiddleware(reducers);
// Approach B.
// const storeWithMiddleware = createStore(
// reducers,
// applyMiddleware(sagaMiddleware, ReduxPromise)
// );
// const store = storeWithMiddleware;
sagaMiddleware.run(rootSaga);
ReactDOM.render(
<Provider store={ store }>
<BrowserRouter>
<Switch>
<Route path="*" render={ (history) => <Wrapper namespace={ namespace }><WrapComponent history={ history } /></Wrapper> } />
</Switch>
</BrowserRouter>
</Provider>
,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
It seems redux-saga wasn't properly installed. Fixed with:
yarn add redux-saga

rendering two different components in react way

I am trying to add the react sticky header to my stepper.
if I try to render bot the components together I am getting an error.
so I debugged and rendering separately.
when I render separately I am not facing an error. store is not defined
can you tell me how to fix it.
so that in future I will fix it myself.
providing my code snippet and sandbox below
https://codesandbox.io/s/y2kjpl343z
index.js
import React from "react";
import ReactDOM from "react-dom";
import Demo from "./demo";
import App from "./components/App";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from 'redux'
// const store = createStore(
// reducer,
// applyMiddleware(thunk, logger)
// )
//ReactDOM.render(<Demo />, document.querySelector("#root"));
render(
<Provider store={store}>
<App />
<Demo />
</Provider>,
document.getElementById("root")
);
You have to define a redux store to pass down to the Provider component.
To define a store, you need to have at least a reducer, I am going to create a fake one now, you'll create your own later:
import React from "react";
import ReactDOM from "react-dom";
import Demo from "./demo";
import App from "./components/App";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { createStore } from 'redux'
const reducer = () => ({})
const store = createStore(reducer)
render(
<Provider store={store}>
<App />
<Demo />
</Provider>,
document.getElementById("root")
);
Update after your comment
If you don't need to use redux, just use a div, or better, a Fragment:
import React, { Fragment } from "react";
import ReactDOM from "react-dom";
import Demo from "./demo";
import App from "./components/App";
ReactDOM.render(
<Fragment>
<App />
<Demo />
</Fragment>,
document.getElementById("root")
);
Because you didn't create a store using the redux function : createStore. Before being able to use redux, you first need to create a reducer to give to your Provider.
Example from the documentation :
import { createStore } from 'redux'
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}
const store = createStore(todos, ['Use Redux'])
render(
<Provider store={store}>
<App />
<Demo />
</Provider>,
document.getElementById("root")
);
You are passing a store variable to the Provider component, but never define it.
Create new file:
import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
const rootReducer = combineReducers({
// You can fill here all the states that you want
})
export const store =
createStore(
rootReducer,
compose(
applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f)
);
Now import the file to your index.js
import store from './store';

Categories