I'm tranfer reactjs project to nextjs with react-redux, redux, nexti18next, next-redux-wrapper here is _app.js and redux.js it run right but if i add withRedux it is error. Please tell me how to resolve this problem or advide me some solution!
import React from "react";
import App, { Container } from "next/app";
import { appWithTranslation } from "../i18n";
import ScrollToTop from "../components/ScrollToTop";
import { createBrowserHistory } from "history";
import { Provider } from "react-redux";
import storeConfig from "../redux";
import compose from "recompose/compose";
const history = createBrowserHistory();
const store = storeConfig();
import withRedux from "next-redux-wrapper";
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
render() {
const { Component, pageProps } = this.props;
console.log(store)
return (
<Container>
<ScrollToTop>
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</ScrollToTop>
</Container>
);
}
}
export default compose(appWithTranslation)(MyApp);
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import getQuote, { initGetQuoteState } from './Modules/GetQuote';
import getSlider, { initGetSliderState } from './Modules/GetSlider';
import getUser, {initGetUserState } from './Modules/User';
import {composeWithDevTools } from 'redux-devtools-extension'
const initState = {
getQuote: initGetQuoteState,
getSlider: initGetSliderState,
getUser: initGetUserState
};
const rooteReducer = combineReducers({
getQuote,
getSlider,
getUser
});
const store = () => createStore(rooteReducer, initState, composeWithDevTools(applyMiddleware(thunk)))
export default store;
Here is example of NextJS/Typescript/Redux/Styled-Components/next-i18next app sample.
// _app.tsx
import * as React from "react";
import App, { AppInitialProps, AppContext } from "next/app";
import withRedux from "next-redux-wrapper";
import { Provider } from "react-redux";
import { ThemeProvider } from "styled-components";
import { theme } from "#Definitions/Styled";
import { appWithTranslation } from "#Server/i18n";
import { AppWithStore } from "#Interfaces";
import { makeStore } from "#Redux";
import "#Static/css/main.scss";
class ProgressiveWebApp extends App<AppWithStore> {
static async getInitialProps({
Component,
ctx,
}: AppContext): Promise<AppInitialProps> {
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
}
render() {
const { Component, pageProps, store } = this.props;
return (
<Provider store={store}>
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
</Provider>
);
}
}
export default withRedux(makeStore)(appWithTranslation(ProgressiveWebApp));
//i18.ts
import NextI18Next from "next-i18next";
const NextI18NextInstance = new NextI18Next({
defaultLanguage: "en",
otherLanguages: ["es"],
});
export const {
appWithTranslation,
withTranslation,
useTranslation,
i18n,
} = NextI18NextInstance;
export default NextI18NextInstance;
and I have path alias in tsconfig
"paths": {
"#Definitions/*": ["definitions/*"],
"#Interfaces": ["interfaces"],
"#Redux": ["redux-store"],
"#Server/*": ["server/*"]
}
hope this helps somebody!
Related
My Expo React Native project is continuously crashing on real device after building.
I used redux saga and its other dependencies for state management and for api call. I used documentation for to learn about. I dont have much knowledge about it.
App.js file
import { SafeAreaView } from "react-native";
import { NativeBaseProvider } from "native-base";
import { InsideStack } from "./src/stackNavigator";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { store, persistor } from "./src/store";
const config = {
strictMode: "warn",
};
function App() {
return (
<SafeAreaView style={{ flex: 1 }}>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<NativeBaseProvider config={config}>
<InsideStack />
</NativeBaseProvider>
</PersistGate>
</Provider>
</SafeAreaView>
);
}
export default App;
Redux index file
import { applyMiddleware } from "redux";
import { legacy_createStore as createStore } from "redux";
import createSagaMiddleware from "redux-saga";
import { persistStore, persistReducer } from "redux-persist";
import AsyncStorage from "#react-native-async-storage/async-storage";
import rootSagas from "./RootSagas";
import { rootReducer } from "./RootReducer";
const sagaMiddleware = createSagaMiddleware();
const persistConfig = {
key: "root",
storage: AsyncStorage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer, applyMiddleware(sagaMiddleware));
let persistor = persistStore(store);
sagaMiddleware.run(rootSagas);
export { store, persistor };
root reducer
import { combineReducers } from "#reduxjs/toolkit";
import MainReducer from "../screens/redux/reducers";
export const rootReducer = combineReducers({
mainreducer: MainReducer,
});
Root saga
import { takeEvery, all, fork, SelectEffect, select } from "redux-saga/effects";
import MainSagas from "../screens/redux/saga";
function* watchAndLog() {
yield takeEvery("*", function* logger(action) {
const state = yield select();
console.debug("action", action);
console.debug("state after", state);
});
}
export default function* root() {
console.log(process.env.NODE_ENV);
const allForks = [fork(MainSagas)];
if (process.env.NODE_ENV === "development") {
allForks.unshift(fork(watchAndLog));
}
yield all(allForks);
}
I'm using mobile-detect library and this tutorial:
link
/src/utiles/isMobile.tsx:
import MobileDetect from "mobile-detect";
import { GetServerSidePropsContext } from "next";
export const getIsSsrMobile = (context: GetServerSidePropsContext) => {
const md = new MobileDetect(context.req.headers["user-agent"] as string);
return Boolean(md.mobile());
};
/src/hooks/useIsMobile.js:
import { useContext } from "react";
import { IsSsrMobileContext } from "../contexts/isSsrMobileContext";
export const useIsMobile = () => {
const isSsrMobile = useContext(IsSsrMobileContext);
return isSsrMobile;
};
/src/contexts/isSsrMobileContext.js:
import { createContext } from "react";
export const IsSsrMobileContext = createContext(false);
my `_app.tsx`:
import { IsSsrMobileContext } from "./../src/contexts/isSsrMobileContext";
function MyApp({ Component, pageProps }: AppProps <{ isSsrMobile: boolean }>): JSX.Element {
return (
<IsSsrMobileContext.Provider value={pageProps.isSsrMobile}>
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</IsSsrMobileContext.Provider>
);
}
export default MyApp;
inside my pages/index.tsx:
console.log("useIsMobile",useIsMobile())
It shows null.
Halo, i'm very confuse with this condition.. i already set cookies if user was regist or login before.. but if i refresh the page.. the cookie was not read and not directed to page that i set before
my code is
import "bootstrap/dist/css/bootstrap.min.css";
import { useStore } from "../src/redux/store";
import { Provider } from "react-redux";
import { useEffect } from "react";
import { authService } from "../src/services/AuthServices";
import { useRouter } from "next/router";
import { SSRProvider } from "react-bootstrap";
function MyApp({ Component, pageProps }) {
const store = useStore(pageProps.initialReduxState);
const dataAuth = authService.isLogin();
const router = useRouter();
const routeList = ["/login"];
useEffect(() => {
if (!dataAuth) {
router.push("/");
}
}, []);
return (
<SSRProvider>
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</SSRProvider>
);
}
export default MyApp;
does anyone can help ?
My question is about why my Cities component in React project do not see any props. What is wrong here? Also i can't understand why reducer do not update state from axios async. What is wrong here?
Here is github link for this project: https://github.com/technoiswatchingyou/reg-form-demo
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { citiesRequestReducer } from './citiesRequestReducer';
const rootReducer = combineReducers({
cities: citiesRequestReducer
});
const store = createStore(rootReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import './App.css';
import Cities from './cities';
class App extends Component {
render() {
return (
<div className="App">
<Cities />
</div>
);
}
}
export default App;
cities.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { citiesRequestAction } from './citiesRequestAction';
import { bindActionCreators } from 'redux';
class Cities extends Component {
componentDidMount() {
this.props.onCitiesRequest();
console.log(this.props);
}
render() {
return (
<select className="custom-select">
{this.props.cities.map(city => (
<option key={city.id}>{city.name}</option>
))}
</select>
);
}
}
const mapStateToProps = state => ({
cities: state.cities
});
const mapDispatchToProps = dispatch => {
return bindActionCreators(
{
onCitiesRequest: citiesRequestAction
},
dispatch
);
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Cities);
citiesRequestReducer.js
import { CITIES_REQUEST } from './citiesRequestAction';
const initialState = [];
export function citiesRequestReducer(state = initialState, action) {
switch (action.type) {
case CITIES_REQUEST:
return {
...state,
cities: action.payload
};
default:
return state;
}
}
citiesRequestAction.js
import axios from 'axios';
export const CITIES_REQUEST = 'CITIES_REQUEST';
const GET_CITIES_URL = 'https://www.mocky.io/v2/5b34c0d82f00007400376066?mocky-delay=700ms';
function citiesRequest(cities) {
return {
type: CITIES_REQUEST,
payload: cities
};
}
export function citiesRequestAction() {
return dispatch => {
axios.get(GET_CITIES_URL).then(response => {
dispatch(citiesRequest(response.data.cities));
});
};
}
So problem was in citiesRequestReducer. Instead of return {...state, cities: action.payload} I just need to return action.payload.
I cant figure out what is going on. I have redux-thunk setup just like always. For some reason that I can not figure out I get the error: Error: Actions must be plain objects. Use custom middleware for async actions. can anyone help me figure this error out?
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
CreateStore.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
export default function configureStore(initialState) {
return createStore(
reducers,
initialState,
applyMiddleware(thunk)
);
}
app.js
import React, { Component } from 'react';
import Routes from './Routes';
import {Provider} from 'react-redux';
import configureStore from './configureStore';
const store = configureStore();
class App extends Component {
render(){
return (
<Provider store={store}>
<Routes/>
</Provider>
);
}
}
export default App;
Today.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { autoLocate } from '../actions';
import { Button } from './Common'
class Today extends Component {
componentDidMount() {
this.props.fetchTodayWeather('http://
api.wunderground.com/api/cc9e7fcca25e2
ded/geolookup/q/autoip.json');
}
render() {
return (
<div>
<div style={styles.Layout}>
<div><Button> HAHAH </Button></div>
<div><Button> Weather Now </Button></div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
const loading = state.locate.loading;
const located = state.locate.autolocation;
return{ loading, located };
};
const mapDispatchToProps = (dispatch) => {
return {
fetchTodayWeather:(Url) => dispatch(autoLocate(Url))
};
};
export default connect(mapStateToProps,mapDispatchToProps)(Today);`
autoLocate.js
import { AUTODATA,
AUTOLOCATING
} from './types';
export const autoLocate = (url) => {
return (dispatch) => {
dispatch({ type: AUTOLOCATING });
fetch(url)
.then(data => fetchSuccess(dispatch, data))
};
};
const fetchSuccess = (dispatch, data) => {
dispatch({
type: AUTODATA,
payload: data
});
};