i'm using the app dir in next js 13 and redux. i have multiple redux reducers so i needed to combine them using next-redux-wrapper package. when using the old way with export default wrapper.withRedux(RootLayout); it works but not for other browsers. and it shows a warning /!\ You are using legacy implementaion. Please update your code: use createWrapper() and wrapper.useWrappedStore().. so i updated the code in my layout.js.
"use client";
import { ChakraProvider } from "#chakra-ui/react";
import "../styles/globals.css";
import { Provider } from "react-redux";
import { wrapper } from "../store";
function RootLayout({ children }) {
const { store } = wrapper.useWrappedStore();
return (
<html>
<head />
<body className="max-w-7xl mx-auto">
<Provider store={store}>
<ChakraProvider>{children}</ChakraProvider>
</Provider>
</body>
</html>
);
}
export default RootLayout;
but when i use this it show there is an error on const { store } = wrapper.useWrappedStore(); line TypeError: Cannot read properties of undefined (reading 'initialState'). so how can i use redux with Next JS 13?
store.js
import { combineReducers, configureStore } from "#reduxjs/toolkit";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import menuReducer from "./slices/menuSlice";
import livingReducer from "./slices/livingSlice";
import {} from "react-redux";
import { ActionTypes } from "#mui/base";
const combinedReducer = combineReducers({
menu: menuReducer,
living: livingReducer,
});
const reducer = (state, action) => {
if (ActionTypes.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
return combinedReducer(state, action);
}
};
const store = configureStore({
reducer: reducer,
});
const makeStore = () => store;
export const wrapper = createWrapper(makeStore);
please any help
From looking at the source code for useWrappedStore, it is expecting the initial state to be passed into the function call. Something like this:
const { store } = wrapper.useWrappedStore({ initialState: { foo: "bar" } });
This should fix your error.
Related
This is a simplified example I've made.
I have the following react component
Test.tsx
import * as React from 'react';
import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../app/hooks';
import { selectTest, setTest } from './testslice';
const Test: React.FunctionComponent = (props) => {
const vals = useAppSelector(selectTest)
const dispatch = useAppDispatch()
useEffect(() => {
dispatch(setTest(["2","3","4","5"]))
},[])
return <>
{vals.map((v,i) => <button key={i}>{v}</button>)}
</>;
};
export default Test;
And the following redux reducer slice
testSlice.ts
import { createSlice, PayloadAction } from "#reduxjs/toolkit";
import { RootState } from "../app/store";
export interface AppState {
test:string[]
}
const initialState: AppState = {
test:[]
};
export const appSlice = createSlice({
name: 'test',
initialState,
reducers: {
setTest(state,action: PayloadAction<string[]>) {
state.test = action.payload
}
},
});
export const {
setTest,
} = appSlice.actions;
export const selectTest = (state: RootState) => state.test.test;
export default appSlice.reducer;
I would like to test the Test component and see, that the buttons are rendered with the values I've dispatched to the redux store (The length of values will be a fixed length)
Test.test.tsx
import React from 'react';
import { render } from '#testing-library/react';
import { Provider } from 'react-redux';
import { store } from '../app/store';
import Test from './TestComponent';
test('renders learn react link', () => {
const { getByText } = render(
<Provider store={store}>
<Test/>
</Provider>
);
//Somehow test that the buttons rendered in <Test/> component have the values dispatched in the useEffect hook
});
How can I achieve this?
Please have a look at the official documentation of testing redux with react and testing library. The idea is to create a preloadedState which gets injected in your application from inside the test. You can then test for the objects of this preloadedState and see if the objects are rendered correctly. After setting up the helper render function in the docs above with e.g.
...
import appReducer from 'PATH/testSlice';
...
store = configureStore({ reducer: { test: appReducer }, preloadedState })
you can then do:
...
import { render } from '../../test-utils'
...
const givenState = { test: ["1", "2", "3"] }
const { getByText } = render( <Test/>, { preloadedState: givenState });
for(const val of givenState.test) {
expect(getByText(val).toBeVisible();
}
For more "integration"-testing, you could also mock return values from functions that finally populate the state, e.g. fetch calls. That way, you would not need to create a preloadedState but mock the fetch calls, whose objects you would use for assertions.
I am new to Next.js, So I follow some tutorials for Redux integration in Next.js. All is working fine but whenever I switch between pages, each time API make a call, and Redux lost its stored value.
The basic function is like this. Whenever a user loads a website an API call will fetch category data from the server and save that data in reducer[categoryReducer], then the user can navigate to any page and category data will fetched from the reducer. But in my case, it hits again and again
Full Code:
// Action Call
import * as Constants from '../../constant/constant';
import * as t from '../types';
import axios from 'axios';
export const loadCategoryApi = (type) => dispatch => {
axios.post(Constants.getCategories,type)
.then(function (response) {
console.log(response);
if(response && response.data && response.data.status==="200"){
dispatch({
type: t.LOAD_CATEGORY,
value: type
});
}
else if(response && response.data && response.data.status==="404"){
alert('Someting went wrong');
}
})
}
// Reducer File
import * as t from '../types';
const initialState = {
doc:null
}
const CategoryReducer = (state = initialState, action) =>{
console.log('reducer action', action.type);
switch (action.type){
case t.LOAD_CATEGORY:
console.log('slots actions',action);
return({...state, doc:action.value})
default:
return state;
}
}
export default CategoryReducer;
// Store file
import { createStore, applyMiddleware, compose } from "redux"
import thunk from "redux-thunk"
import { createWrapper } from "next-redux-wrapper"
import rootReducer from "./reducers/rootReducer"
const middleware = [thunk]
const makeStore = () => createStore(rootReducer, compose(applyMiddleware(...middleware)))
export const wrapper = createWrapper(makeStore);
// rootReducer
import { combineReducers } from "redux"
import CategoryReducer from "./CategoryReducer";
const rootReducer = combineReducers({
CategoryReducer: CategoryReducer
})
export default rootReducer;
// _app.js
import React from "react"
import { wrapper } from "../redux/store"
import Layout from '../components/Layout';
import '../styles/globals.css'
const MyApp = ({ Component, pageProps }) =>(
<Layout>
<Component {...pageProps} />
</Layout>
);
export default wrapper.withRedux(MyApp);
// Uses
import React, { useState, useEffect } from 'react';
import {connect} from "react-redux";
import {loadCategoryApi} from "../redux/actions/CategoryAction";
function navbar(props){
const { loadCategory, loadCategoryApi } = props;
useEffect(() => {
if(loadCategory===null){
console.log('navbar loading funciton');
loadCategoryFunation();
}
}, []);
const loadCategoryFunation = () =>{
var json = {
type : 'main'
};
loadCategoryApi(json);
}
}
const mapStateToProps = state => {
return { loadCategory: state.CategoryReducer.doc }
}
const mapDispatchToProps = {
loadCategoryApi
}
export default connect(mapStateToProps, mapDispatchToProps)(Navbar)
What I am doing wrong?
You have to create main reducer to handle the hydration. I explained this hydration process here.
In the file that you created the store, write main reducer
import reducers from "./reducers/reducers";
const reducer = (state, action) => {
// hydration is a process of filling an object with some data
// this is called when server side request happens
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
// whenever we deal with static rendering or client side rendering, this will be the case
// reducers is the combinedReducers
return reducers(state, action);
}
};
then pass this reducer to the store
I want to separate modules, so I tried to separate files in the src/store/modules directory.
To merge reducer modules, I use combineReducers() in modules/index.js.
Before separating these modules, modules/index.js file's code was modules/board.js.
Then I added board.js file. I moved code of index.js to board.js. Finally I added combineReducer() in index.js, but somehow it is not working.
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import store from './store';
const rootElement = document.getElementById('root');
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
src/containers/BoardContainer.js
import React from 'react';
import Board from '../components/Board';
import { connect } from 'react-redux';
import * as boardActions from '../store/modules/board';
class BoardContainer extends React.Component {
componentWillMount() {
this.props.handleReadBoards();
}
render() {
/* ... */
}
}
const mapStateToProps = (state) => {
return {
boardList: state.get('boardList')
};
}
const mapDispatchToProps = (dispatch) => {
return {
handleReadBoards: () => { dispatch(boardActions.readBoardList()) }
};
}
export default connect(mapStateToProps, mapDispatchToProps)(BoardContainer);
src/store/index.js
// redux
import { createStore, applyMiddleware, compose } from 'redux';
import reducers from './modules';
// redux middleware
import thunk from 'redux-thunk';
const store = createStore(reducers,
compose(applyMiddleware(thunk))
);
export default store;
src/store/modules/index.js
import { combineReducers } from 'redux';
import board from './board';
export default combineReducers({
board
});
src/store/modules/board.js
import { createAction, handleActions } from 'redux-actions';
import { Map, List } from 'immutable';
import * as boardApi from '../../lib/api/board';
// Action Types
const READ_BOARD_LIST = 'board/READ_BOARD_LIST';
// Action Creators
export const readBoardList = () => async (dispatch) => {
try {
const boardList = await boardApi.getBoardList();
dispatch({
type: READ_BOARD_LIST,
payload: boardList
});
} catch (err) {
console.log(err);
}
}
// initial state
const initialState = Map({
boardList: List()
})
// reducer
// export default handleActions({
// [READ_BOARD_LIST]: (state, action) => {
// const boardList = state.get('boardList');
// return state.set('boardList', action.payload.data);
// },
// }, initialState);
// reducer
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case READ_BOARD_LIST:
return state.set('boardList', action.payload.data);
default:
return state;
}
}
Your reducer now contains submodules. So that you have to state from which module you want to get the data: state.board.get('boardList').
You can try to setup redux tool to easy visualize your data inside redux.
const mapStateToProps = (state) => {
return {
boardList: state.board.get('boardList')
};
}
I am trying to create something similar to todo app with react and redux from here.I have been reading all the solutions for this problem and nothing seems to be working for my case.
Most of the solutions purpose using Provider which I am already using. Any help is much appreciated.
Edit - Few import statement might be missing in snippets, but all components are being imported whenever needed and actions are also defined in action file.
Index.js
import App from './components/App'
import reducer from './reducers/index'
const store = createStore(reducer)
const AppWithStore = (
<Provider store={store}>
<App />
</Provider>
)
ReactDOM.render(AppWithStore, document.getElementById('root'))
Update - Combined Reducer code
import React from 'react'
import { combineReducers } from 'redux'
import TestReducer from './TestReducer'
export default combineReducers({
TestReducer,
})
App.js
import Test from './Test';
class App extends Component {
render() {
return (
<Test />
);}
}
ReactDOM.render(
(<App/>),
document.getElementById("root")
);
export default App
Test.js contains both component and container
import { connect } from 'react-redux'
import { add } from '../actions'
const mapStateToProps = state => ({
todos: state.todos,
})
class Test extends Component {
dosomething() {
const dispatch = this.props;
dispatch(add("New Note"));
}
render() {
return (
<div>
< button OnClick = { this.dosomething.bind(this)} > Test </button>
</div>
)
}
}
export default connect(mapStateToProps)(Test)
The reducer logic for Test is as given below
import React from 'react';
const TestReducer = (state = [], action) => {
const todos = state;
const {type, payload} = action;
switch(action.type){
case 'ADD': {
return {
...state,
todos:"new todo"
}
}
}
return state;
}
export default TestReducer
You should remove
ReactDOM.render(
(<App/>),
document.getElementById("root")
); from App.js file
When you call it again in App.js a new component instance independent of others is created, That's why it is not finding store.As store is not passed to it.
You can check it here https://codesandbox.io/s/vy7wwqw570. As i had remove render api call from app.js it is working now.
you need to import your reducers so that you
if your file name is TestReducer.js
import React from 'react';
export const TestReducer = (state = [], action) => {
const todos = state;
const {type, payload} = action;
switch(action.type){
case 'ADD': {
return {
...state,
todos:"new todo"
}
}
}
return state;
}
then import it in this manner
import {TestReducer} from './TestReducer.js';
const store = createStore(TestReducer);
Try replacing todos: state.todos with todos: state.TestReducer.todos
import { connect } from 'react-redux'
import { add } from '../actions'
const mapStateToProps = state => ({
//todos: state.todos,
todos: state.TestReducer.todos
})
class Test extends Component {
dosomething() {
const dispatch = this.props;
dispatch(add("New Note"));
}
render() {
return (
<div>
< button OnClick = { this.dosomething.bind(this)} > Test </button>
</div>
)
}
}
export default connect(mapStateToProps)(Test)
I've spent a couple of days now searching for the answer to this and I still don't know what I'm doing wrong. I have other projects set up in exactly the same way that are fetching data from api's fine. All other answers have said variations of how the actions need to return objects, which as far as I can tell mine are
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { createLogger } from 'redux-logger';
import Thunk from 'redux-thunk';
import reducer from './reducers/reducer';
import App from './App';
import './css/index.css';
import './css/font-awesome.css';
import './css/bulma.css';
const logger = createLogger();
const store = createStore(reducer, applyMiddleware(Thunk, logger));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
Component calling mapDispatchToProps
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { searchRepositories } from '../actions/searchActions';
class Results extends Component {
componentDidMount() {
this.props.searchRepositories();
}
render() {
return (
<div>Some Stuff</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
searchRepositories: () => {
dispatch(searchRepositories());
},
};
};
const mapStateToProps = (state) => {
return {
repositories: state.repositories,
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Results);
Reducer:
import * as types from '../actions/types';
import initialState from './INITIAL_STATE';
function reducer(prevState = initialState, action) {
if (!action) return prevState;
switch (action.type) {
case types.FETCH_REPOS_REQUEST:
return { ...prevState, loading: true };
case types.FETCH_REPOS_SUCCESS:
return {
...prevState,
loading: false,
repositories: action.data,
error: '',
};
case types.FETCH_REPOS_ERROR:
return { ...prevState, error: 'Encountered an error during GET request' };
default:
return prevState;
}
}
export default reducer;
action creator:
import axios from 'axios';
import * as types from './types';
import { ROOT } from '../config';
export function searchRepositoriesRequest() {
return {
type: types.FETCH_REPOS_REQUEST,
};
}
export function searchRepositoriesSuccess(repositories) {
return {
type: types.FETCH_REPOS_SUCCESS,
data: repositories,
};
}
export function searchRepositoriesError(error) {
return {
type: types.FETCH_REPOS_ERROR,
data: error,
};
}
export function searchRepositories() {
return function (dispatch) {
dispatch(searchRepositoriesRequest());
return axios.get(`${ROOT}topic:ruby+topic:rails`).then((res) => {
dispatch(searchRepositoriesSuccess(res.data));
}).catch((err) => {
dispatch(searchRepositoriesError(err));
});
};
}
I have got this axios api request working using react this.state where I just put it in component did mount. If anyone can see where I am going wrong it would help me out a lot.
Ok, so it looks like I was using an earlier version of redux, which the version of redux-thunk I had installed, didn't like! I updated to the latest version of redux and it now calls as it should.
I'm still not sure why the other projects that have the older version installed still work...