React Redux Hooks not finding State - reactjs

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

Related

Redux: useSelector returns undefined

I have carefully gone through my code, nothing wrong with store, reducer function, Provider, but useSelector hook returns undefined in the App.js. Why does it return undefined?
redux.js
import {createStore} from 'redux'
const counterReducer = (state = {counter:0}, action)=>{
if(action.type ==='increment'){
return {counter:state.counter+1}
}
if(action.type ==='decrement'){
return{counter : state.counter-1}
}
}
const store = createStore(counterReducer);
export default store;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import store from '../src/store/redux'
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store = {store}>
<App />
</Provider>,
document.getElementById('root')
);
reportWebVitals();
App.js
import './App.css';
import {useSelector} from 'react-redux'
function App() {
const counter = useSelector(state=> state);
console.log(counter) //undefined
return (
<div></div>
);
}
export default App;
redux.js
import { createStore } from 'redux';
const counterReducer = (state = { counter: 0 }, action) => {
**// Updated previous if statement using switch statement**
switch (action.type) {
case 'increment':
return { ...state, counter: state.counter + 1 };
case 'decrement':
return { ...state, counter: state.counter - 1 };
default:
return { counter: 0 }; // you need to define a default value;
}
const store = createStore(counterReducer);
export default store;
app.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import './style.css';
export default function App() {
const counter = useSelector((state) => state.counter);
const dispatch = useDispatch();
console.log(counter);
return (
<div>
<h1>{counter}</h1>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
Look at this code, we always need a default value when creating reducer. Using switch statement for this case I think safe.
you can see this solution: stackbllitz

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();

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
}
}

Redux, connect method not working. Data not fetched from store

I am learning redux. I have written an application for the same, first time. I am not able to understand why data isnt being fetched from store. Is there anything wrong with my connect call? Please help.
I am getting error that contactsList is undefined while calling map below, although connect should fetch that list as per my understanding.
ContactCards.js
import React, { Component } from 'react';
import Card from './Card';
import { connect } from 'react-redux';
const CardList = ({ contactsList }) => {
const cardsArray = contactsList.map(contact => (
<Card
key={contact.id}
name={contact.name}
email={contact.email}
phone={contact.phone}
website={contact.website}
city={contact.address.city}
companyName={contact.company.name}
id={contact.id} />
));
return (
<div className="jumbotron">
<div className='card-columns'>
{cardsArray}
</div>
</div>
);
};
const mapStateToProps = state => {
return { contactsList: state.contactsList };
};
const ContactCards = connect(mapStateToProps)(CardList);
export default ContactCards;
Reducer dataReducer
import ContactsList from '../components/MockContactsList';
import {loadContacts, updateContacts} from '../Actions/CardActions';
const INITIAL_STATE = {
contactsList: ContactsList
};
const dataReducer = (state = INITIAL_STATE, action) => {
switch(action.type) {
case loadContacts:
return state;
case updateContacts:
const updatedItems = state.contactsList.map(item => {
if(item.id === action.id){
return { ...item, ...action.payload }
}
return item
})
return updatedItems;
default:
return state;
}
};
export default dataReducer;
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import reducers from './reducers/index';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const store = createStore(reducers, {});
ReactDOM.render(
<Provider store = {store}>
<App />
</Provider>
,document.getElementById('root'));
registerServiceWorker();
Reducers index.js
import { combineReducers } from 'redux';
import dataReducer from './dataReducer';
export default combineReducers({
dataReducer
});
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import reducers from './reducers/index';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const store = createStore(reducers, {});
ReactDOM.render(
<Provider store = {store}>
<App />
</Provider>
,document.getElementById('root'));
registerServiceWorker();
You must first access your reducer state (dataReducer) then its property:
const mapStateToProps = state => {
return { contactsList: state.dataReducer.contactsList };
};
In your store you have a key of dataReducer:
export default combineReducers({
dataReducer
});
But you're accessing it as contactsList here:
const mapStateToProps = state => {
return { contactsList: state.contactsList };
};
So you probably need to have that key in your store instead:
export default combineReducers({
contactsList: dataReducer
});

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

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.

Resources