React + Redux Example. Object are not valid as a React child - reactjs

I am having trouble getting a simple React and Redux example working and need some help please. I am receiving the following error as soon as I attempt to dispatch the incrementNumber action. I will paste my code in below. Or you can use the Github link here. Thanks in advance!
index.js (App root)
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import store from './store/configureStore';
import App from './containers/App';
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
configureStore.js
import { createStore } from 'redux';
import rootReducer from '../reducers';
export default createStore(rootReducer);
index.js (root reducer)
import { combineReducers } from 'redux';
import numbersReducer from './numbersReducer';
const rootReducer = combineReducers({
number: numbersReducer
});
export default rootReducer;
numbersReducer.js
import initialState from './initialState';
export default function numbersReducer(state = initialState.number, action) {
switch (action.type) {
case "INCREMENT_NUMBER":
return { ...state, number: state.number + 1 }
default:
return state;
}
}
initialState.js
export default {
number: 0
}
App.js
import React from 'react';
import { connect } from 'react-redux';
import { incrementNumber } from '../actions/appActions';
export class App extends React.Component {
componentDidMount() {
this.props.dispatch(incrementNumber(1));
}
render() {
return (
<div>
Current number: {this.props.number}
</div>
);
}
}
const mapStateToProps = state => ({
number: state.number
});
export default connect(mapStateToProps)(App);
appActions.js
export function incrementNumber(number) {
return { type: "INCREMENT_NUMBER", number}
}

<div>
Current number: {this.props.number.number}
</div>
and also change this.
export default function numbersReducer(state = initialState, action) {
switch (action.type) {
case "INCREMENT_NUMBER": {
return { ...state, number: state.number + 1 }
}
default:
return state;
}
}
/* state = initialState */

const rootReducer = combineReducers({
number: numbersReducer
});
In combineReducers argument object, "number" can't be property. Because numbersReducer already have this property "number" in it's initialState.

Related

TypeError: store.getState is not a function. (In 'store.getState()', 'store.getState' is undefined)

Hi guys i was setting up redux in my react native project but facing some issues while setup even though i am pretty sure i haven't used getState till now but as ssons as app runs i get error
TypeError: store.getState is not a function. (In 'store.getState()',
'store.getState' is undefined)
my code is as
reducers / hireducer.js
import { HI } from "../constants";
const initialState = {
count: 0,
};
const countReducer = (state = initialState, action) => {
switch (action.type) {
case HI:
return {
...state,
count: action.payload,
};
default:
return state;
}
};
export default countReducer;
reducers / index.js
import { combineReducers } from "redux";
import hiReducer from "./hireducer.js";
export default combineReducers({
hi: hiReducer,
});
store / configStore
import { createStore } from "redux";
import reducers from "../reducers/index";
const configureStore = () => {
return createStore(reducers);
};
export default configureStore;
App.js
import "react-native-gesture-handler";
import React from "react";
import { NavigationContainer } from "#react-navigation/native";
import AuthNavigator from "./navigations/AuthNavigation";
import { withHOC } from "./index.js";
function App() {
return (
<NavigationContainer>
<AuthNavigator />
</NavigationContainer>
);
}
export default withHOC(App);
index.js
import React from "react";
import { Provider } from "react-redux";
import configStore from "./redux/store/configStore";
export const withHOC = (App) => (props) => {
return (
<Provider store={configStore}>
<App {...props} />
</Provider>
);
};
even though if i normally wrap in without providing store i still get the same error
Your configStore returns a function instead of a store object.
So you rather call the function in your app like
<Provider store={configStore()}>
<App {...props} />
</Provider>
Or you create a store object from configStore like
const configureStore = () => {
return createStore(reducers);
};
export default configureStore();

React Redux Hooks not finding State

I'm following this
https://react-redux.js.org/api/hooks
I get state undefined, i connected my store or i think i did. i dont know what is the issue. The reducer code is inconsequetial. I'm just trying to return anything to get some kind of helloo world. I have used react redux before.
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux';
import { createStore,} from 'redux';
import reducers from './js/reducers';
const store = createStore(reducers);
ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById('root')
);
//App.js
function App() {
const data = useSelector(state.myReducerData)
return (
<div>{data}</div>
);
}
export default App
//reducers/index.js
import { combineReducers } from 'redux';
import {OneReducer} from "./ExampleReducers"
const rootReducer = combineReducers({
myReducerData: OneReducer
});
export default rootReducer;
//ExampleReducers.js
import {EXAMPLES} from "../actions/types";
export function OneReducer (state = {}, action) {
switch (action.type) {
case EXAMPLES:
return action.payload
default:
return state
}
return state;
}
You're missing reducer initial state for one.
import { EXAMPLES } from "../actions/types";
// declare it here.
const initialState = {
data:[]
};
export function OneReducer(state = initialState, action) {
switch (action.type) {
case EXAMPLES:
return action.payload;
default:
return state;
}
return state;
}
and you can try this
const data = useSelector((state) => state.data) // refers to initial state data property

React Redux doesn't update UI

React-Redux doesn't update UI when store changes.
I expect {this.props.isLogged} to get changed dynamically when Change button is clicked.
I searched tons of materials but I cannot find why the text doesn't change when button is clicked.
Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { createStore } from "redux";
import reducers from "./reducers";
import { Provider } from "react-redux";
const store = createStore(
reducers);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
App.js
import React from "react";
import { connect } from "react-redux";
import { loginUser } from "./actions";
class App extends React.Component {
changeText = () => {
this.props.loginUser();
};
render() {
return (
<div>
<span>{this.props.isLogged}</span>
<button onClick={this.changeText}>Change</button>
</div>
);
}
}
const mapStateToProps = (state /*, ownProps*/) => {
return {
isLogged: state.isLogged
};
};
const mapDispatchToProps = { loginUser };
export default connect(mapStateToProps, mapDispatchToProps)(App);
./src/reducers/index.js
import { combineReducers } from "redux";
import { LOGIN_USER } from "../actions";
function userReducer(state = { isLogged: false }, action) {
switch (action.type) {
case LOGIN_USER:
return { isLogged: !state.isLogged };
default:
return state;
}
}
const reducers = combineReducers({
userReducer
});
export default reducers;
./src/actions/index.js
export const LOGIN_USER = "LOGIN_USER";
export function loginUser(text) {
return { type: LOGIN_USER };
}
Check this out..
https://codesandbox.io/s/react-redux-doesnt-update-ui-vj3eh
const reducers = combineReducers({
userReducer //It is actually userReducer: userReducer
});
As you assiging your UserReducer to userReducer prop, you will have to fetch the same way in mapStateToProps
const mapStateToProps = (state /*, ownProps*/) => {
return {
isLogged: state.userReducer.isLogged
};
};
Also, isLogged prop is a Boolean variable.. So you are gonna have to use toString().
<span>{this.props.isLogged.toString()}</span>
Since you are using combineReducers, the isLogged boolean lives in state.userReducer.isLogged.
Consider changing combineReducers to combineReducers({ user: userReducer }) and accessing the flag with state.user.isLogged.

Unhandled Rejection (Error) reducer is returning undefined

Server throws error "Unhandled Rejection" while rendering Search Component. I had put return statement on both of the case while writing reducers.
Code in Action File:
export const NEWS = "NEWS";
export function news(items) {
const action = {
type: NEWS,
items
}
return action;
}
Code in Reducer File:
import { NEWS } from '../actions';
export default function news
(state = [], action) {
switch(action.type) {
case NEWS:
console.log("News are ",action.items);
return {...state, news: action.items};
default:
return state;
}
}
This is my search function.
class Search extends Component {
constructor(props) {
super(props);
this.state = {
query: ''
};
}
search(){
console.log('Search button clicked', this.state.query);
const url = `http://hn.algolia.com/api/v1/search?query=${this.state.query}`;
// console.log(url);
fetch(url, {
method: 'GET'
}).then(response=> response.json())
.then(jsonObj => {this.props.news(jsonObj.results)});
}
This is NewsResults.js code where I am using mapStateToProps function
import React, { Component } from 'react';
import Search from './Search';
import { connect } from 'react-redux';
class NewsResults extends Component {
render() {
return (
<div>
<h2>
Search Results:
</h2>
<Search/>
</div>
)
}
};
function mapStateToProps(state) {
console.log(state)
return {
news: state.news
}
};
export default connect(mapStateToProps, null)(NewsResults);
** This is what my redux store looks like in index.js**
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root'));
registerServiceWorker();
The state you are giving to the reducer is a list, to which you are assigning values as if it were an object. change the reducer to have state = initialState = {}
const initialState = {}
export default function (state = initialState, action) {
switch (action.type) {
// your cases
default:
return state
}
}

Cannot get value from Redux store

I'm having trouble retrieving data from the Redux store. Redux logger is showing the data but can't seem to get it to render. Below is the code for my container component and my action/reducer:
//COMPONENT:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchGrade } from '../../modules/smiles';
class Main extends Component {
componentDidMount() {
this.props.fetchSmile();
console.log(this.props);
}
render() {
const { smiles } = this.props;
return (
<div>
<h1>This is the Main Component</h1>
</div>
);
}
}
const mapStateToProps = state => {
return { smiles: state.smiles };
};
const mapDispatchToProps = dispatch => {
return {
fetchSmile: params => dispatch(fetchGrade(params))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Main);
//ACTION/REDUCER:
import axios from 'axios';
const ADD_GRADE = 'SMILES/ADD_GRADE';
export function reducer(state = {}, action) {
switch (action.type) {
case ADD_GRADE:
return {
...state,
grade: action.payload
};
default:
return state;
}
}
export const fetchGrade = () => {
return dispatch => {
axios
.get('/api/test')
.then(res => dispatch({ type: ADD_GRADE, payload: res.data }));
};
};
//STORE:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import logger from 'redux-logger';
import reducer from '../modules';
let store;
export function configureStore(state: {}) {
if (!store) {
store = createStore(
reducer,
state,
composeWithDevTools(applyMiddleware(logger, thunk))
);
}
return store;
}
//INDEX.JS:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import { configureStore } from './store';
window.store = configureStore();
render(
<Provider store={window.store}>
<App />
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
I really don't know if this is complicated or an easy fix. I feel like I'm doing everything right but no luck.
You named your reducer, reducer:
export function reducer(state = {}, action) {
Seems that you forgot to access it from your reducer object. it should be something like this:
const mapStateToProps = state => {
return { smiles: state.reducer.smiles };
};

Resources