I built a chrome extension with react.js and webpack.config.js . now I want add redux to my project but I don't know how to configure with redux
I just find the reduxed-chrome-storage npm package but I don't know how to configure
First, you need to install the dependencies for Redux and the reduxed-chrome-storage package:
npm install --save redux reduxed-chrome-storage
Create a store.js file where you will configure your Redux store. In this file, you will import the necessary dependencies and define the store.
import { createStore, applyMiddleware } from 'redux';
import storage from 'reduxed-chrome-storage';
const store = createStore(
rootReducer,
applyMiddleware(storage.middleware)
);
export default store;
Connect your React components to the Redux store by using the react-redux library. You will need to wrap your root component with the Provider component and pass the store as a prop.
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
function App() {
return (
<Provider store={store}>
{/* your application code */}
</Provider>
);
}
export default App;
Finally, you need to add the reduxed-chrome-storage enhancer to the store. This will allow the store to be persisted to Chrome storage:
import { createStore, applyMiddleware } from 'redux';
import storage from 'reduxed-chrome-storage';
const store = createStore(
rootReducer,
applyMiddleware(storage.middleware),
storage.enhancer
);
export default store;
This is the basic configuration for using Redux with your Chrome extension. You can now start using Redux in your application.
Related
I have a react app that uses sessions with an express server using REST API.
In my Redux store(on the front end) I store "isLoggedIn" in the redux state. Based on that property I show either the login page , or the home page. Now when I open the website, the initial redux "isLoggedIn" state is false, so the question is, how do I check if the user is actually logged in. I am thinking about sending a request to the endpoint for fetching the data I need in the homepage, and if the user is not logged in, I would get an 401 response and then show the login page. Is this the correct approach?
Before I get into how you could persist your redux state I would advise(Note This is a personal view)
Going through the boiler plate code of setting that up is really unnecessarily long
Best way out for this is using express-session whereby the cookie is persisted for as long as you gave it e.g if you set cookie to be 3days it will stay for 3days
I so believe that it's industry standard working with httpOnly cookie for session handling as this is secure avoiding XSS attacks and CSRF attacks
Either way below is your solution to persisting Redux Store
So with persisting your redux state you can look into something like this
First run npm install redux-persist or yarn add redux-persist
Now time to create your redux store
So now when you create your redux store with createStore you want to pass your createStore function a persistReducer Once your store is created, pass it to the persistStore function, which will make sure that your redux state is persisted
Implementation below
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import rootReducer from './reducers';
//Import above comes from a file **reducers** which has the combineReducers
// basically based on this code snippet
// I have my combineReducer object in another folder hope that it
//makes sense. Avoided to write it here to keep code short to show
//more of setup in store persisiting
const persistStoreConfigs = {
key: 'root',
storage: myAppStorage,
stateReconciler: autoMergeLevel2
};
const persistantReducer = persistReducer(persistStoreConfigs, rootReducer);
export const store = createStore(persistantReducer);
export const persistor = persistStore(store);
Now passing the store to the App level
import React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/lib/integration/react';
// This are coming from the store code above that we made
import { persistor, store } from './store';
// This are basically your Custom Componentd
import { HomePage, LoadingView } from './components';
const App = () => {
return (
<Provider store={store}>
// the loading and persistor props are both required!
// Noting that the LoadingView is a custom component
// But the persistor isn't
//The main aim of this two props is to delay the rendering of your app UI until the persited state is retrieved hence the loading screen component
<PersistGate loading={<LoadingView />} persistor={persistor}>
<HomePage />
</PersistGate>
</Provider>
);
};
export default App;
So I have been creating an application where a user needs to log into firebase using google authentication. I am using redux, react-redux, react-redux-firebase, redux-firestore, and redux-thunk. I am able to successfully log the user into firebase with the google authentication. I now want to use firestore in order to have a collection of all the users. I have looked at the documentation for redux-firestore and the method of getting/manipulating is a little different. I have tried using the documentation, but I cannot get the functions to work with redux-firestore.
Here is the action
export const signIn = () => (
dispatch,
getState,
{getFirebase, getFirestore}) => {
const firebase = getFirebase();
const firestore = getFirestore();
firebase.auth().signInWithPopup(provider).then(function(result) {
if(result.credential) {
firestore.get({collection: 'users', doc: result.user.uid}).then(function(doc) {
if(!doc.exists){
console.log("new!")
firestore.add(
{collection: 'users', doc: result.user.uid},
{name: firebase.auth.currentUser.displayName});
} else{
console.log("old!")
}
})
}
}).catch((err) => {
})
};
And here is my setup in index.js for the src folder
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {BrowserRouter} from 'react-router-dom';
import {createStore, applyMiddleware, compose} from 'redux';
import {Provider} from 'react-redux';
import allReducers from './reducers';
import thunk from 'redux-thunk';
import firebase from './Firebase';
import {firebaseConfig} from './Firebase'
import {createFirestoreInstance, getFirestore, reduxFirestore} from 'redux-firestore';
import {ReactReduxFirebaseProvider, getFirebase} from 'react-redux-firebase';
const store = createStore(
allReducers,
compose(
applyMiddleware(thunk.withExtraArgument({getFirebase, getFirestore})),
reduxFirestore(firebaseConfig)
));
const rrfConfig = {
userProfile: 'users',
useFirestoreForProfile: true
};
const rrfProps = {
firebase,
config: rrfConfig,
dispatch: store.dispatch,
}
ReactDOM.render(
<Provider store={store}>
<ReactReduxFirebaseProvider {...rrfProps}>
<BrowserRouter>
<App />
</BrowserRouter>
</ReactReduxFirebaseProvider>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
I know that I have not used createFirestoreInstance in this code, but I was playing around with it.
If anyone could tell me how to get this working, I would appreciate it.
Thanks!
Quick update:
I have figured out how to at least write to firestore using this code
const userRef = firebase.firestore().collection('users').doc(result.user.uid);
userRef.get().then(function(doc) {
if(!doc.exists){
userRef.set({name: result.user.displayName});
}
})
This is not the best (or maybe the right solution), but it does work. It is not using redux-firestore, but is there a better way?
If you're using React, use react-redux-firebase. There's no need for these many complication and the code looks much neater and simpler. Authentication, firestore and all other firebase features works out of the box with just small amount of code. They also comes with React hooks like useFirebase() and useFirestore() instead of you needing to write them on your own.
react-redux-firebase is built on top of redux-firebase and provides all the things you would need in React.
If your app only uses firebase, I would even recommend you use just plain Redux without Redux Thunk or Redux Saga.
I'm trying to integrate simpreWebRTC to my React-Redux project, but the library has their own redux store and the documentation says this:
"The provided createStore function makes a basic Redux
store useful for getting things started. If you want to
make your own, import reducer from '#andyet/simplewebrtc' and
be sure to assign it to simplewebrtc in the top level of
your state object."
I've tried several approaches but nothing works, any idea? what I'm missing here?
Thanks
This is the code that I have so far:
store.js
import {createStore, applyMiddleware} from 'redux'
import rootReducer from './reducers/index'
import thunk from 'redux-thunk';
export default createStore(rootReducer, applyMiddleware(thunk));
const store = createStore(rootReducer);
console.log(store.getState());
./reducers/index.js
import {combineReducers} from 'redux'
import {reducer as simplewertc} from '#andyet/simplewebrtc'
import liveRoomReducer from './liveRoomReducer'
export default combineReducers({simplewertc, liveRoomReducer});
./reducers/liveRoomReducer.js
const initialState = {
test : 'test'
};
export default function liveRoomReducer(state=initialState, action) {
return state;
};
I'm logging the store state in the console and is showing simplewebrtc on it:
And still showing this error:
Creating your own store with thunk middleware and using combineReducers should do the trick:
import {combineReducers} from 'redux';
import {reducer as simplewebrtc} from '#andyet/simplewebrtc';
import reducer1 from 'path/to/your/reducer1';
import reducer2 from 'path/to/your/reducer2';
export default combineReducers({simplewebrtc, reducer1 , reducer2});
If that isn't working for you please provide what error is showing up if any and some example code of how you create your redux store and root reducer.
Edit: After seeing the updated question with code, we found the problem was in a typo when importing the reducer.
import * as React from 'react';
import { Provider } from 'react-redux';
import type { Store } from 'redux';
import configureStore from './configureStore';
export const store: Store<*, *> = configureStore();
function CustomProvider(children: React.Node) {
return <Provider store={store}>{children}</Provider>;
}
export default CustomProvider;
I have this flow-erorr:
[flow] React element Provider (This type is incompatible with)
What type i am need to use for Provider?
Which version of flow do you use?
I just created a new empty project and added your code to my App.js and flow doesn't complain.
I used flow-bin ^0.56.0 in my package.json.
I fully reinstalled all my application and now I have a problem to build react application.
The problem file has the following view:
import React from "react";
import ReactDOM from "react-dom";
import {Provider} from "react-redux";
import {createStore, combineReducers, applyMiddleware} from "redux";
import createLogger from "redux-logger";
import App from "./components/App.jsx";
import * as reducers from "./reducers";
import types from "./constants/actions";
import message from "./constants/message";
import mid from "./middleWare/mid";
const logger = createLogger();
const reducer = combineReducers(reducers);
const store = createStore(
reducer,
{
userName: 'N/A',
error: '',
info: '',
services: [],
carwashes: [],
backUrl : ''
},
applyMiddleware(mid, logger)
);
const destination = document.querySelector("#container");
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
destination
);
Do you have any idea what was missed ?
React, redux and react-redux were installed
This looks more like an issue with es6. You may be missing some of the babel packages you may have had globally installed. Fully delete the node_modules folder and then do a yarn install.
This is not complaining about the Provider, it's complaining about the < arrow