Provider fails to pass down state as props in react-redux - javascript

I am trying to create a searchbox here, using redux but everytime I run the code, which appears to be flawless, some error creeps in. It shows that the state is undefined, followed by an error in webpack_require file from the node modules. Another time, it showed that the searchField is not defined. Any assistance would be highly appreciated.
Actions:
import { CHANGE_SEARCH_FIELD } from './constants.js';
export const setSearchField=(text)=>({
type: CHANGE_SEARCH_FIELD,
payload: text
})
Reducers:
import { CHANGE_SEARCH_FIELD} from './constants.js';
const initialState={
searchField: ''
}
export const searchRobots=(state=initialState, action={})=>{
switch(action.type){
case CHANGE_SEARCH_FIELD:
return Object.assign({},state,{searchField: action.payload});
default: return state;
}
}
index.js:
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import './index.css';
import 'tachyons';
import App from './App.js'
import * as serviceWorker from './serviceWorker';
import {searchRobots} from './reducers.js';
const store= createStore(searchRobots);
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
serviceWorker.register();
Container:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import CardList from './CardList';
import SearchBox from './SearchBox';
import Scroll from './Scroll';
import {setSearchField} from './actions.js'
import './App.css';
const mapStateToProps=(state)=>{
return {
searchField: state.searchRobots.searchField
}
}
const mapDispatchToProps=(dispatch)=>{
return {
onSearchChange: (event)=>{
dispatch(setSearchField(event.target.value))
}
}
}
class App extends Component{
constructor(){
super()
this.state={
robots: [],
}
}
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(
response=>{return response.json();}
)
.then(
users=>{this.setState({robots: users});}
);
}
render(){
const {searchField,onSearchChange}=this.props;
const filteredRobots= this.state.robots.filter(robot=>{return robot.name.toLowerCase().includes(searchField.toLowerCase())});
return(
<div className='tc'>
<h1 id="robo">ROBOFRIENDS</h1>
<SearchBox searchChange={onSearchChange}/>
<Scroll>
<CardList robots={filteredRobots} />
</Scroll>
</div>
);
};
}
export default connect(mapStateToProps,mapDispatchToProps)(App);
Any leads about the error would be highly appreciated

Related

React Redux -> TypeError: Object(...) is not a function

So I'm learning react and I've split my code into seperate files which are, as follows ->ReduxDemo.js/reducers.js/store.js/actions.js
Here is their content:
ReduxDemo.js:
import React from 'react'
import {useSelector} from 'react-redux'
function ReduxDemo(){
const cakeAmount = useSelector(state=>state.cakeCount)
return(
<div>
<div>
<h1>Amount of cakes - {cakeAmount}</h1>
</div>
</div>)
}
export default ReduxDemo;
reducers.js:
import {combineReducers} from 'redux'
const cakeState=
{
cakeCount: 10,
}
const iceCreamState=
{
iceCreamCount: 20
}
const cakeReducer=(state={cakeState},action)=>
{
switch(action.type)
{
case 'buyCake':
return{
...state,
cakeCount: state.cakeCount -1
}
default:
return state
}
}
const iceCreamReducer=(state=iceCreamState, action)=>
{
switch(action.type)
{
case 'buyIceCream':
return{
...state,
iceCreamCount: state.iceCreamCount-1
}
default:
return state;
}
}
const reducers = combineReducers(
{
cake: cakeReducer,
iceCream: iceCreamReducer
})
export default reducers;
store.js:
import reducers from './reducers'
import {createStore} from 'react'
const store = createStore(reducers)
store.subscribe(()=>
{
console.log('store changed:', store.getState())
})
export default store;
actions.js:
import store from './store'
export const buyCake=()=>
{
store.dispatch({type: 'buyCake'})
}
App.js:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import ReduxDemo from './ReduxDemo'
import {Provider} from 'react-redux'
import store from './store'
function App() {
return (
<div>
<Provider store={store}>
<ReduxDemo></ReduxDemo>
</Provider>
</div>
);
}
export default App;
for some obscure to me reason I get "TypeError: Object(...) is not a function", that is supposedly located at this line in store.js -> const store = createStore(reducers) Why is that and how can I fix it?
createStore is not a function offered by React. You need to import it from Redux:
// store.js
import { createStore } from 'redux'

createStore function returns undefined store object

I am very new to React Native and in the process of creating some sample apps. So following a tutorial app, i was trying to create a Taxi Booking App that has redux store involved in it.
So my App.js file looks as below:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Root from "./src/main";
export default class TaxiApp extends Component {
render() {
return (
<View style={styles.container}>
<Root {...this.props}/>
</View>
);
}
}
The main.js file is as follows:
import React from "react";
import createStore from "./store/createStore";
import AppContainer from "./AppContainer";
export default class Root extends React.Component{
renderApp(){
const initialState = window.___INITIAL_STATE__;
const store = createStore(initialState);
return(
<AppContainer store={store}/>
);
}
render(){
return this.renderApp();
}
}
The AppContainer component is as follows:
import React, {Component, PropTypes} from "react";
import {Router} from "react-native-router-flux";
import {Provider} from "react-redux";
import scenes from "../routes/scenes";
export default class AppContainer extends Component{
static propTypes = {
store : PropTypes.object.isRequired
}
render(){
return(
<Provider store={this.props.store}>
<Router scenes={scenes}/>
</Provider>
)
}
}
The createStore() function for the Root component is as follows:
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import makeRootReducer from "./reducers";
import { createLogger } from "redux-logger";
import createSocketIoMiddleware from "redux-socket.io";
import io from "socket.io-client/dist/socket.io";
let socket = io("http://localhost:3000", {jsonp:false});
let socketIoMiddleware = createSocketIoMiddleware(socket, "server/");
const log = createLogger({ diff: true, collapsed: true });
// a function which can create our store and auto-persist the data
export default (initialState = {}) => {
// ======================================================
// Middleware Configuration
// ======================================================
const middleware = [thunk, log, socketIoMiddleware];
// ======================================================
// Store Enhancers
// ======================================================
const enhancers = [];
// ======================================================
// Store Instantiation
// ======================================================
const store = createStore(
makeRootReducer(),
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
);
return store;
};
On trying to run this in the android emulator I am getting the following error:
undefined is not an object(evaluating '_react.PropTypes.object')
It would be great if someone could help. Thanks in advance!!!
You need to do the following
import PropTypes from 'prop-types';
remove import proptypes from the react package

Given action "Movies_List", reducer returned undefined

i'm working on my first react app with react, react-router and redux also...
here i'm trying to make a app which is showing movies name. and i don't know what am i doing wrong..
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers';
import App from './app';
const createStoreWithMiddleware = applyMiddleware()(createStore)
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
src/app.js
import React, {Component} from 'react';
import MoviesList from './containers/movies_list';
class App extends Component {
render(){
return(
<div>
<MoviesList />
</div>
)
}
}
export default App;
src/reducers/index.js
import { combineReducers } from 'redux';
import movies from './movies_reducer';
const rootReducer = combineReducers(
{movies}
);
export default rootReducer;
src/reducers/movies_reducer.js
export default function(state = null, action){
switch(action.type){
case'MOVIES_LIST':
return action.payload;
default:
return state;
}
}
src/action.index.js
export function moviesList() {
return{
type: 'MOVIES_LIST',
payLoad: [
{id:1, name:"Lagan"},
{id:2, name:"Robot"},
{id:3, name:"Gold"}
]
}
}
src/containers/movies_list.js
import React, {Component} from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
class MoviesList extends Component {
componentWillMount(){
this.props.moviesList()
}
renderList = (movies) => {
if(movies){
return movies.map((movie) => {
return(
<div>{movie.name}</div>
)
})
}
}
render(){
return(
<div>
{this.renderList(this.props.movies)}
</div>
)
}
}
function mapStateToProps(state){[![enter image description here][1]][1]
console.log(state)
return{
movies:state.movies
}
}
export default connect(mapStateToProps,actions)(MoviesList);
it shows error like this...
bundle.js image of the error
You have a typo in your moviesList() action creator (pay attention to payLoad => payload):
export function moviesList() {
return {
type: 'MOVIES_LIST',
payload: [
{id:1, name:"Lagan"},
{id:2, name:"Robot"},
{id:3, name:"Gold"},
],
};
}

React Native with Redux-Persist , PersistGate inifinite loading

I'm working on an app in react native and must work with Redux-Persist. I have the store configuration set up, no errors occur but the rehydration never happens and the persistentGate is infinitely in the loading state.
Here is my store.js
import { createStore, combineReducers } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import entriesReducer from './reducers/entries';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
const rootReducer = combineReducers({
entries : entriesReducer
});
const persistConfig = {
key: 'root',
storage: storage,
stateReconciler: autoMergeLevel2 // see "Merge Process" section for details.
};
const pr = persistReducer(persistConfig, rootReducer);
const configureStore = () => {
const store = createStore(rootReducer);
const persistor = persistStore(store);
return { persistor, store };
};
export default configureStore;
And my index.js
import React from 'react';
import { AppRegistry } from 'react-native';
import {Provider} from 'react-redux';
import App from './App';
import configureStore from './src/store/configureStore';
import { PersistGate } from 'redux-persist/lib/integration/react';
const store = configureStore();
const RNRedux = () => (
<Provider store={store.store}>
<PersistGate loading={<App />} persistor={store.persistor}>
<App/>
</PersistGate>
</Provider>
);
AppRegistry.registerComponent('PTM', () => RNRedux);
Any help will be very much appreciated, I've been trying to set this up for days now with no success. Previously I would have to deal with errors but now I don't see any and it still refuses to work, I simply don't know where to look for the fault.
Edit:
App.js file
import React from 'react';
import { View, Text, Button, StatusBar } from 'react-native';
import { StackNavigator } from 'react-navigation';
import {connect} from 'react-redux';
import NavBar from './src/components/NavBar/NavBar';
import DayPicker from './src/components/DayPicker/DayPicker';
import TotalTime from './src/components/TotalTime/TotalTime';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';
import EntriesList from './src/components/EntriesList/EntriesList';
var x = null;
const RootStack = StackNavigator(
{
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
And my HomeScreen is using this:
const mapStateToProps = state => {
return {
data : state.entries.data,
entriesPerDay : state.entries.entriesPerDay,
pickedDate : state.entries.pickedDate,
total: state.entries.total
};
};
const mapDispatchToProps = dispatch => {
return {
onPickDate: (day) => dispatch(pickDay(day)),
onDataSet: (data) => dispatch(setData(data))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);

React-native-Redux: could not find stored in either the context or props of connect(componentName)

I'm getting below error even i had defined store for root component.
click to enlarge image
Not sure why im getting this error even after defining store.
index.js (rootpage)
import React, {Component} from 'react';
import {initStore} from './redux/store';
import {Provider} from 'react-redux';
import App from './App.container';
const store = initStore();
class BuddApp extends Component {
render () {
return (
<Provider store={store}>
<App />
</Provider>
);
}
}
export default BuddApp;
This is app.container.js which is inside app.
app/app.container.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Router from './routes';
import Proptypes from 'prop-types';
import {addNavigationHelpers} from 'react-navigation';
class App extends Component {
render () {
const {dispatch, nav, userPreferences} = this.props;
console.log(this.props)
return (
<Router screenProps={userPreferences} navigation={addNavigationHelpers({dispatch, state: nav})}/>
</Provider>
);
}
}
App.propTypes = {
dispatch: Proptypes.func,
nav: Proptypes.object,
userPreferences: Proptypes.object
};
const mapStateToProps = ({nav, userPreferences}) => ({
nav,
userPreferences
});
const mapDispatchToProps = (dispatch) => ({
dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
app/pages/login.page.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import Login from '../components/Login/Login.component';
import {NavigationActions} from 'react-navigation';
class LoginPage extends Component {
onLoginPress(){
console.log("fsdfds")
this.props.navigation.navigate('setupProfile')
}
render () {
const {state} = this.props;
return (
<Login onLoginPress={this.onLoginPress.bind(this)} />
);
}
}
LoginPage.propTypes = {
onLoginPress: PropTypes.func
};
const mapStateToProps = (state) => ({
state:state
});
const mapDispatchToProps = (dispatch) => ({
saveLoginDetails: dispatch(addProfile(f))
});
export default connect(mapStateToProps,mapDispatchToProps)(LoginPage);
This results in getting the above mentioned error. as you can see I am passing the store in the same manner as shown in the redux example.
Am i defined store in wrong file?
Try this way:
import { createStore, applyMiddleware } from "redux"
const store = createStore(
<<Your combined reducers comes here>>,
applyMiddleware(<<All your middleware comes here>>))

Categories

Resources