How would I set up my reducer properly? - javascript

I'm trying to toggle my modal via redux but for some reason I'm getting an error that says: TypeError: Cannot read property 'isModalOpen' of undefined (pointing to the line isOpen: state.global.isModalOpen inside List.js) which means my root reducer isn't defined properly. But I'm sure I've defined it properly inside index.js file. What am I doing wrong and how would I be able to resolve this and use these actiontypes properly in order for it to work?
Note: The <Modal/> component is an npm package I installed, I didn't create it on my own.
Here's my List.js file:
import React, { Component } from 'react';
import Aux from '../../../../hoc/Aux';
import { connect } from 'react-redux';
import Modal from 'react-modal';
class List extends Component {
state = {
isOpen: false
}
componentWillMount() {
Modal.setAppElement('body');
}
toggleModal = () => {
this.setState({isActive:!this.state.isActive});
}
closeModal = () => {
this.setState({isActive: false});
}
render() {
return (
<Aux>
<CheckoutButton clicked={this.toggleModal}/>
<Modal isOpen={this.state.isOpen}>
<button onClick={this.closeModal}>Close</button>
</Modal>
</Aux>
);
}
}
const mapStateToProps = state => {
return {
isOpen: state.global.isModalOpen
}
};
const mapDispatchToProps = dispatch => {
return {
closeModalRedux: () => dispatch({type: CLOSE_MODAL})
}
};
export default connect(mapStateToProps, mapDispatchToProps)(List);
Here's my reducer.js file:
import React from 'react';
import * as actionTypes from '../action/NoNameAction';
const initialState = {
isModalOpen: false
};
const global = (state = initialState, action) => {
switch(action.type) {
case actionTypes.OPEN_MODAL:
return {
...state,
isModalOpen: true,
}
case actionTypes.CLOSE_MODAL:
return {
...state,
isModalOpen: false,
}
default:
return state;
}
};
export default global;
Here's my index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import modalOpenReducer from './store/reducer/reducer';
const rootReducer = combineReducers({
isOpen: modalOpenReducer
});
const store = createStore(rootReducer);
ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));
registerServiceWorker();

change the reducer file name to global.js and in the root.js import it as global instead of reducer.And also in the component,change to this.props.isOpen

Related

Ă— TypeError: Cannot read properties of undefined (reading 'getState')

I am a beginner learning react and redux. I wrote this demo about how to use connect.js in redux. Searching this kind of question but there is no right answer for my code. I got a undefined context. Is it typo? or I passed context in a wrong way? Thanks in advance. Here is my code.
index.js
import React from "react";
import ReactDOM from "react-dom";
import store from "./store";
import { Provider } from "react-redux";
import App from "./App";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
/store/index.js
import { createStore } from "redux";
import reducer from "./reducer.js";
const store = createStore(reducer);
export default store;
/store/reducer.js
import { ADD, SUB, MUL, DIV } from './constants.js'
// or initialState
const defaultState = {
counter: 0
}
function reducer(state = defaultState, action) {
switch (action.type) {
case ADD:
return {...state, counter: state.counter + action.num};
case SUB:
return {...state, counter: state.counter - action.num};
case MUL:
return {...state, counter: state.counter * action.num};
case DIV:
return {...state, counter: state.counter / action.num};
default:
return state;
}
}
export default reducer
connect.js
import React, { PureComponent } from "react";
import { StoreContext } from "./context";
export default function connect(mapStateToProps, mapDispatchToProps) {
return function enhanceHOC(WrappedCpn) {
class EnhanceCpn extends PureComponent {
constructor(props, context) {
super(props, context);
console.log('connect props', props);
console.log('connect context', context); // context is undefined here
this.state = {
storeState: mapStateToProps(context.getState()),
};
}
componentDidMount() {
this.unSubscribe = this.context.subscribe(() => {
this.setState({
counter: mapStateToProps(this.context.getState()),
});
});
}
componentWillUnmount() {
this.unSubscribe();
}
render() {
return (
<WrappedCpn
{...this.props}
{...mapStateToProps(this.context.getState())}
{...mapDispatchToProps(this.context.dispatch)}
/>
);
}
}
EnhanceCpn.contextType = StoreContext;
return EnhanceCpn;
};
}
context.js
import React from "react";
const StoreContext = React.createContext();
export {
StoreContext
}
App.js
import React, { PureComponent } from 'react'
import My from './pages/my'
export default class App extends PureComponent {
constructor(props, context) {
super(props, context);
console.log('APP props', props);
console.log('APP context', context); // context got value
}
render() {
return (
<div>
<My />
</div>
)
}
}
my.js
import React, { PureComponent } from 'react'
import { sub, mul } from '../store/actionCreators'
import connect from '../utils/connect'
class My extends PureComponent {
render() {
return (
<div>
<h3>my</h3>
<h3>counter: { this.props.counter }</h3>
<button onClick={e => this.props.subNum()}>-2</button>
<button onClick={e => this.props.mulNUm(5)}>*5</button>
</div>
)
}
}
const mapStateToProps = state => ({
counter: state.counter
})
const mapDispatchToProps = dispatch => ({
subNum: (num = -2) => {
dispatch(sub(num))
},
mulNUm: num => {
dispatch(mul(num))
}
})
export default connect(mapStateToProps, mapDispatchToProps)(My)
actionCreators.js
import { ADD, SUB, MUL, DIV } from './constants.js'
export function add(num) {
return {
type: ADD,
num
}
}
export const sub = (num) => {
return {
type: SUB,
num
}
}
export const mul = (num) => ({
type: MUL,
num
})
export const div = num => ({
type: DIV,
num
})
constants.js
const ADD = 'ADD_ACTION'
const SUB = 'SUB_ACTION'
const MUL = 'MUL_ACTION'
const DIV = 'DIV_ACTION'
export { ADD, SUB, MUL, DIV }
From the docs, here is what it says with regards to Class.contextType:
The contextType property on a class can be assigned a Context object
created by React.createContext(). Using this property lets you
consume the nearest current value of that Context type using
this.context. You can reference this in any of the lifecycle methods
including the render function.
It seems that in your case, you are just missing passing your custom StoreContext to redux Provider with the context props
You need to do something like:
import React from "react";
import ReactDOM from "react-dom";
import store from "./store";
import { StoreContext } from "./context";
import { Provider } from "react-redux";
import App from "./App";
ReactDOM.render(
<Provider store={store} context={StoreContext}>
<App />
</Provider>,
document.getElementById("root")
);
See also https://react-redux.js.org/using-react-redux/accessing-store#providing-custom-context
I got the same issue and solved by creating store on the same file as the root component where Provider is applied. Example code below:
<Provider store={createStore(reducers)}>
<App />
</Provider>
Cannot read properties of undefined (reading 'getState')
Solution:
(1) make a file store.js in your redux folder and you can copy the code
import { createStore, applyMiddleware } from "redux";
import logger from 'redux-logger';
import rootReducer from "./root-reducer";
const middlewares = [logger];
const store = createStore(rootReducer, applyMiddleware(...middlewares));
export default store;
(2) then just import the file in index.js file
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
i got same issues
i just have to change were i have my configure store from this
import { configureStore } from "#reduxjs/toolkit";
import basketReducer from "../slices/basketSlice";
export const store = configureStore({
reducer: {
basket: basketReducer,
},
});
to this
import { configureStore } from "#reduxjs/toolkit";
import basketReducer from "../slices/basketSlice";
export default configureStore({
reducer: {
basket: basketReducer,
},
});
and this method works for me
i also find out when i play around with the code to understand why it happen and see if i broke it what will happen this is my finding and observation from it
note concerning redux
if you used the below as import in your _app.js
import { store } from "../stores/store";
then
the global store should be rewritten like this
export const store = configureStore({
reducer: {
basket: basketReducer,
},
});
but if you import it like this with out distructuring it[store] or without the curly bracket
import store from "../stores/store";
then
you should write the store like this
export default configureStore({
reducer: {
basket: basketReducer,
},
});
Both ways works for me

Redux Thunk for simple async requests

I am building a simple app to retrieve some recipes from an API URL.
I am reading the documentation of Thunk to implement it but I cannot understand how to set the async get request.
What is strange is that if I console.log the action passed into the reducer it definitely retrieves the correct object (a list of recipes for shredded chicken).
When I pass the action onto the the reducer, instead, it throws the error:
"Unhandled Rejection (Error): Given action "FETCH_RECIPES", reducer "recipes" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined."
Is there any error in my action creator? is the API call properly done?
Store
import React from 'react';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import SearchBar from './components/App';
import thunk from 'redux-thunk';
import 'bootstrap/dist/css/bootstrap.css';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
render(
<Provider store={store}>
<SearchBar />
</Provider>,
document.getElementById('root')
)
Component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './App.css';
import { Button } from 'reactstrap';
import { Form } from 'reactstrap';
import { bindActionCreators } from 'redux';
import {fetchRecipe } from '../actions';
class SearchBar extends Component {
constructor(props) {
super(props)
this.state = { term: ''};
this.typeRecipe = this.typeRecipe.bind(this)
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
e.preventDefault()
this.props.fetchRecipe(this.state.term)
}
typeRecipe(e) {
this.setState({term: e.target.value});
}
render() {
return (
<div className="SearchBar">
<Form onSubmit={this.onFormSubmit}>
<input type='text'
value={this.state.term}
placeholder='ciao'
onChange={this.typeRecipe}
/>
<br/>
<Button id='ciao' className='btn-success'>Submit</Button>
</Form>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchRecipe }, dispatch);
}
export default connect(null, mapDispatchToProps)(SearchBar);
Action creator
import axios from 'axios';
export const FETCH_RECIPES = 'FETCH_RECIPES';
const API_KEY = 'xxx';//not the real one.
export function fetchRecipe() {
const request = axios.get(`http://food2fork.com/api/search?key=${API_KEY}&q=shredded%20chicken`);
return (dispatch) => {
request.then(({data}) =>{
dispatch({ type: FETCH_RECIPES, payload: data})
})
}
}
reducer
import { FETCH_RECIPES } from '../actions';
export default function (state = {}, action) {
switch(action.type) {
case FETCH_RECIPES:
const newState = action.payload.data;
return newState;
default:
return state
}
}
combineReducer (index)
import recipeReducer from '../reducers/recipes_reducer';
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
recipes: recipeReducer
});
export default rootReducer;
Mistake is in the reducer return statement.
export default function (state = {}, action) {
switch(action.type) {
case FETCH_RECIPES:
const newState = {...state, data : action.payload.data};
return newState;
default:
return state
}
}
Here we are adding data key to the reducer state, to access this you can use do this in you container :
export default connect((state)=>{
var mapStateToProps = {};
if(state.recipes.data) {
mapStateToProps['recipes'] = state.recipes.data
}
return mapStateToProps;
}, mapDispatchToProps)(SearchBar);
and recipes data will be available as this.props.recipes.

React.js Redux actions and reducers do not get initated

I am having an issue with my React-Redux app. I have created Redux action & reducer and connected them to my React component. However, it seems like it never gets to my Redux action & reducer.
I put "debugger" in my action and reducer but those debuggers never get initiated.
Could you please help me fix this issue?
Am I missing something here?
Here the current codes in the following files:
Here is the code for my app.js:
import React, { Component } from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import ReduxPromise from 'redux-promise';
import rootReducer from './reducers';
import App from './components/index';
const createStoreWithMiddleware = applyMiddleware(thunk, ReduxPromise)(createStore);
render(
<Provider store={createStoreWithMiddleware(rootReducer)}>
<App />
</Provider>,
document.getElementById('app')
);
Here is my code for index.js:
As you can see below, I put a debugger in the "componentDidMount()", and when In run it, it gets to that point.
import React, { Component } from 'react';
import { render } from 'react-dom';
import { connect } from 'react-redux';
import * as AllNewsApiActions from '../actions/newsApiActions';
import '../../css/style.css';
class App extends Component {
componentDidMount() {
this.props.getNewsApi();
debugger;
}
render() {
return (
<div>
<p>Hello from react</p>
<p>Sample Testing</p>
</div>
);
}
}
const mapStateToProps = (state) => ({
newNews: state.newNews
});
export default connect(mapStateToProps, {
...AllNewsApiActions
})(App);
Here is my action:
import * as types from './newsTypes';
const API_KEY = "6c78608600354f199f3f13ddb0d1e71a";
export const getNewsApi = () => {
debugger;
return (dispatch, getState) => {
dispatch({
type: 'API_REQUEST',
options: {
method: 'GET',
endpoint: `https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=${API_KEY}`,
actionTypes: {
success: types.GET_NEWS_API_SUCCESS,
error: types.GET_NEWS_API_ERROR
}
}
});
}
}
Here is my reducer:
import * as types from '../actions/newsTypes';
const initialState = {
newNews: []
};
const getNewsAPIReducer = (state = initialState, action) => {
switch(action.type) {
case types.GET_NEWS_API_SUCCESS:
debugger;
return { ...state, newNews: action.data };
case types.GET_NEWS_API_ERROR:
debugger;
return { ...state, error: action.data };
default: {
return state;
};
};
};
export default getNewsAPIReducer;
Here is the index.js file in the reducer folder:
import { combineReducers } from 'redux';
import NewsApiReducer from './newsApiReducer.js';
const rootReducer = combineReducers({
newNews: NewsApiReducer
});
export default rootReducer;

Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(CharacterList)

I am trying to test my React "supersquadapp" and getting the following error.
Uncaught Error: Could not find "store" in either the context or props of "Connect(CharacterList)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(CharacterList)".
characterlist.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
class CharacterList extends Component {
render() {
console.log('this.props', this.props);
return (
<div>
<h4>characters</h4>
</div>
)
}
}
function mapStateToProps(state) {
return {
characters: state.characters
}
}
export default connect(mapStateToProps, null)(CharacterList);
app.js
import React, {Component} from 'react';
import CharacterList from './CharacterList';
class App extends Component {
render() {
return (
<div>
<h2>SUPER SQUAD</h2>
<CharacterList />
</div>
)
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './Components/App';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducers from './reducers';
import { addCharacterById } from './actions';
const store = createStore(rootReducers);
console.log(store.getState());
store.subscribe(() => console.log('store',store.getState()))
store.dispatch(addCharacterById(3));
ReactDOM.render(
<Provider>
<App />
</Provider>
,document.getElementById('root')
)
character.js(in reducers folder)
import characters_json from '../Data/characters.json';
import { ADD_CHARACTER } from '../actions';
function characters(state = characters_json, action) {
switch(action.type) {
case ADD_CHARACTER:
let characters = state.filter(item => item.id !== action.id);
return characters;
default:
return state;
}
}
export default characters;
heroes.js(reducers folder)
import { ADD_CHARACTER } from '../actions';
import {createCharacter} from './helper';
function heroes(state = [], action) {
switch(action.type) {
case ADD_CHARACTER:
let heroes = [...state, createCharacter(action.id)];
return heroes;
default:
return state;
}
}
export default heroes;
helper.js(reducers folder)
import characters_json from '../Data/characters.json';
export function createCharacter(id) {
let character = characters_json.find(c => c.id === id);
return character;
}
index.js(reducers folder)
import { combineReducers } from 'redux';
import characters from './characters_reducer';
import heroes from './heroes_reducer';
const rootReducer = combineReducers({
characters,
heroes
})
export default rootReducer;
index.js(action folder)
export const ADD_CHARACTER = 'ADD_CHARACTER';
export function addCharacterById(id) {
const action = {
type:ADD_CHARACTER,
id
}
return action;
}
The above error occurred in the component:
in Connect(CharacterList) (at App.js:9)
in div (at App.js:7)
in App (at index.js:19)
in Provider (at index.js:18)
please help me...?
If you are running a test and you have something like alechill's answer, you'd need this to change in the test, for example:
let mockedStore = configureStore([])({});
test('some test', () => {
const wrapper = mount(<SomeComponent foo="bar" />, {
context: { store: mockedStore },
childContextTypes: { store: PropTypes.object.isRequired }
});
expect(.... your tests here);
});
You must pass the store instance to Provider...
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root')
)

react redux: still getting empty object for this.props when using Connect for mapStateToProps and mapDispatchToProps

I'm trying to follow this tutorial (https://medium.com/#stowball/a-dummys-guide-to-redux-and-thunk-in-react-d8904a7005d3) on React Redux but am getting an empty object when I print out this.props. It seems like mapStateToProps isn't actually setting this.props since react redux's connect isn't being called, but I'm not sure why
This is what the state should be (like in the tutorial), all I did was change the component's name ItemList to Home
Here's what I'm getting (nothing was mapped to the state):
actions/items.js
export function itemsHasErrored(bool) {
return {
type: 'ITEMS_HAS_ERRORED',
hasErrored: bool
};
}
export function itemsIsLoading(bool) {
return {
type: 'ITEMS_IS_LOADING',
isLoading: bool
};
}
export function itemsFetchDataSuccess(items) {
return {
type: 'ITEMS_FETCH_DATA_SUCCESS',
items
};
}
export function itemsFetchData(url) {
return (dispatch) => {
dispatch(itemsIsLoading(true));
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(itemsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((items) => dispatch(itemsFetchDataSuccess(items)))
.catch(() => dispatch(itemsHasErrored(true)));
};
}
components/Home.js
export class Home extends Component {
componentDidMount() {
console.log(this.props)
}
render() {
if (this.props.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <p>Loading…</p>;
}
return (
<ul>
{this.props.items.map((item) => (
<li key={item.id}>
{item.label}
</li>
))}
</ul>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.itemsHasErrored,
isLoading: state.itemsIsLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(itemsFetchData(url))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Home);
reducers/index.js
export function itemsHasErrored(state = false, action) {
switch (action.type) {
case 'ITEMS_HAS_ERRORED':
return action.hasErrored;
default:
return state;
}
}
export function itemsIsLoading(state = false, action) {
switch (action.type) {
case 'ITEMS_IS_LOADING':
return action.isLoading;
default:
return state;
}
}
export function items(state = [], action) {
switch (action.type) {
case 'ITEMS_FETCH_DATA_SUCCESS':
return action.items;
default:
return state;
}
}
store/configureStore.js
import { applyMiddleware, createStore } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
)
}
App.js
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import configureStore from './store/configureStore'
import { Home } from './components/Home'
const store = configureStore()
export default class App extends Component {
render () {
return (
<Provider store={store}>
<Home />
</Provider>
)
}
}
index.js (I am using create-react-app boilerplate)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
The issue is that you're exporting two components... the non-connected (via the named export Home with export class Home...) and connected (via export default). Then, you're importing and rendering the non-connected component:
import { Home } from './components/Home'
Since you want to use the connected component, you should be importing the default export like this:
import Home from './components/Home'
You may want to just export the connected component, unless you have some reason to use the unconnected one.

Categories

Resources