React native, action not dispatching - reactjs

I am trying to dispatch an action to update my state, I am using a picker in my component, I don't get any errors but state doesn't update. Any ideas?
onChange = e => {
setSelectedView(e);
};
const HomeScreen = () => {
return (
<View style={styles.container}>
<Image
source={require("../img/logoGreen.png")}
style={{ width: 150, height: 100 }}
/>
<View style={{ backgroundColor: "red" }}>
<Text>Please select a year</Text>
<Picker selectedValue={0} onValueChange={onChange}>
{studentYears.map((year, i) => {
return (
<Picker.Item
key={year.id}
label={year.title}
value={year.value}
/>
);
})}
</Picker>
</View>
</View>
);
};
const mapStateToProps = state => {
return {
selectedView: state.selectedView
};
};
const mapDispatchToProps = dispatch => {
return {
setSelectedView: e => dispatch(setSelectedView(e))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
Reducer:
export function setSelectedView(state = 0, action) {
switch (action.type) {
case "SET_SELECTED_VIEW":
return action.setSelectedView;
default:
return state;
}
}
Action:
export const setSelectedView = int => ({
type: "SET_SELECTED_VIEW",
selectedView: int
});
Store:
import {
eventsFetchData,
eventsHasErrored,
eventsIsLoading,
eventsFetchDataSuccess,
setSelectedView
} from "../actions/events";
import rootReducer from "../reducers";
const initialState = {
eventsHasErrored: false,
eventsIsLoading: true,
events: [],
setSelectedView: { selectedView: 0 }
};
const reduxLogger = createLogger();
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunk, reduxLogger)
);

I think the problem is in your reducer
export function setSelectedView(state = 0, action) {
switch (action.type) {
case "SET_SELECTED_VIEW":
return action.selectedView;//instead of action.setSelectedView;
default:
return state;
}
}

Related

Why am I getting NaN and how to use Redux in React Native to add items to a FlatList

Hello all I am new to using React Native and Redux and while I feel I am almost wrapping my head around the core concept of redux I am trying to apply it to this application and keep getting lost.
I have yet to incorporate the Flat list efficiently as my MapDispatchToProps is doing visually what I want which is to display the input from the user below when pressing on the the add to list button.
Questions
1st) I cant figure out why I am getting NaN when I add something to the text input?
I have been trying for two days now watching videos and reading documentation
2nd) Any suggestion on how to change my code so that when the user inputs a value it is displayed below via a FlatList?
Really trying to understand what I don't understand so any points would be great.
My Task List component
import {
Text,
View,
Button,
StyleSheet,
TextInput,
SafeAreaView,
FlatList,
} from 'react-native';
import {
newToDo,
addToList,
removeFromList,
reset,
} from '../redux/actions/index';
const TaskList = ({ todo, history, addToList, removeFromList, reset }) => {
return (
<View>
<SafeAreaView>
<TextInput
style={styles.input}
value={todo}
placeholder="Enter Value Here"
/>
<View style={styles.button}>
<Button
title="Add Values to List"
onPress={() => addToList({ todo })}
/>
</View>
<View style={styles.button}>
<Button
title="RemoveFromList"
onPress={() => removeFromList({ todo })}
/>
</View>
<View style={styles.button}>
<Button title="Reset" onPress={() => reset()} />
</View>
{history.map((x) => (
<Text
style={{
borderWidth: 1,
borderColor: 'gray',
borderRadius: 5,
margin: 10,
padding: 5,
}}>
{x}
</Text>
))}
<FlatList
data={newToDo}
renderItem={newToDo}
keyExtractor={(item) => item.toDo}
/>
</SafeAreaView>
</View>
);
};
const styles = StyleSheet.create({
input: {
padding: 5,
textAlign: 'center',
borderWidth: StyleSheet.hairlineWidth * 2,
borderColor: 'gray',
borderStyle: 'solid',
borderRadius: StyleSheet.hairlineWidth * 10,
marginTop: StyleSheet.hairlineWidth * 20,
marginBottom: StyleSheet.hairlineWidth * 20,
},
button: {
margin: 5,
},
});
const MapDispatchToProps = { addToList, removeFromList, reset };
const MapStateToProps = (store) => ({
list: store.listReducer.newToDo,
history: store.listReducer.history,
});
export default connect(MapStateToProps, MapDispatchToProps)(TaskList);
redux folder
actions
import {ADD_TO_LIST, REMOVE_FROM_LIST, RESET_LIST} from '../actionTypes/index';
export const addToList = (newToDo) => {
return {
type: ADD_TO_LIST,
payload: {
toDo: 'newToDo',
},
};
};
export const removeFromList = (newToDo) => {
return {
type: REMOVE_FROM_LIST,
payload: {
toDo: 'newToDo',
},
};
};
export const reset = () => {
return {
type: RESET_LIST,
payload: {
},
};
};
My listReducer
ADD_TO_LIST,
REMOVE_FROM_LIST,
RESET_LIST,
} from '../actionTypes/index';
const initialState = {
history: [],
list:[],
};
export default function (state = initialState, action) {
if (action.type == ADD_TO_LIST) {
return {
...state,
list: state.list - action.payload.toDo,
history: [...state.history, + action.payload.toDo],
};
} else if (action.type == REMOVE_FROM_LIST) {
return {
...state,
list: state.list - action.payload.toDo,
history: [...state.history, - action.payload.toDo],
};
} else if (action.type == RESET_LIST) {
return { ...state, list: 0, history: [] };
}
return state;
}
my Main App
import TaskList from './TaskList/index';
import store from './redux/store';
export default function App() {
return (
<Provider store={store}>
<TaskList />
</Provider>
)
}
Full project available on expo snacks https://snack.expo.dev/#stephaniebrandon/excited-juice-box
First off, why are you trying to minus the action payload in your reducer? If you minus string with an array of course it will return NaN.
return {
...state,
list: state.list - action.payload.todo,
history: [...state.history, -action.payload.newToDo],
};
Secondly, you made a typo in your action. There is no such payload called newToDo in the action payload, only toDo. Update your code to the following in your reducer.
import {
ADD_TO_LIST,
REMOVE_FROM_LIST,
RESET_LIST,
} from '../actionTypes/index';
const initialState = {
history: [],
list:[],
};
export default function (state = initialState, action) {
if (action.type == ADD_TO_LIST) {
return {
...state,
list: [...state.list, action.payload.todo],
history: [...state.history, action.payload.toDo],
};
} else if (action.type == REMOVE_FROM_LIST) {
return {
...state,
list: [...state.list, action.payload.todo],
history: [...state.history, action.payload.toDo],
};
} else if (action.type == RESET_LIST) {
return { ...state, list: 0, history: [] };
}
return state;
}

Redux with React Native state not updating

I tried to add a recipe to favourites using Redux with React Native.
If I use the state in the favicon.js this works fine but does not work with Redux.
This is my favicon.js
import React, {useState} from 'react'
import { FontAwesome } from '#expo/vector-icons'
import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'
import { connect } from 'react-redux'
import { toggleFavId, isFavourite } from '../actions'
const FavIcon = ({recipeid, toggle, isFav, text}) => {
// const [isFavNew, setFavNew] = useState(false)
// const toggleFav = (recipeid) =>{
// setFavNew(!isFavNew)
// console.log(`Entered toggle ${recipeid} isfavnew = ${isFavNew}`)
// }
return (
<View>
<TouchableOpacity style={styles.favItem} onPress={() => {toggle(recipeid)}}>
<FontAwesome name={isFav == true ? 'heart' : 'heart-o'} size={40} color='red' />
<Text> {text}</Text>
</TouchableOpacity>
</View>
)
}
const mapStateToProps = (state) =>({
favids: state.favids,
})
const mapDispatchToProps = (dispatch) => ({
toggle: (recipeid) => dispatch(toggleFavId(recipeid)),
isFav: (recipeid) => dispatch(isFavourite(recipeid)),
})
export default connect(mapStateToProps,mapDispatchToProps)(FavIcon)
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#fff',
alignItems: 'flex-start',
justifyContent: 'center',
},
favItem: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
marginTop:10,
paddingTop:15,
paddingBottom:15,
marginLeft:30,
marginRight:30,
backgroundColor:'#00BCD4',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff',
height: 75,
width: 300,
}
});
This if the reducer....the code enters the TOGGLE switch but the state is not updated with the new values.
import {TOGGLE, IS_FAVOURITE} from '../actions'
export const favids = (state=[], action) => {
const {type, recipeid} = action
const newRecipe = {
recipeid: recipeid,
is_fav: true,
}
switch (type) {
case TOGGLE: {
console.log(`Toggle State = ${JSON.stringify(state)}`)
console.log(`NEW REcipe ${JSON.stringify(newRecipe)} `)
// console.log(`Toggle State after adding = ${JSON.stringify(state)}`)
// return state.map(item=>{
// state.recipeid === recipeid ?
// {...item, newRecipe} : {...item,newRecipe}
// })
return {...state, newRecipe}
}
case IS_FAVOURITE: {
console.log(`Is Favourite state =${JSON.stringify(state)}`)
return state.map(item=>{
item.recipeid === recipeid ?
{...item, is_fav: !item.is_fav} : item
})
}
default:
return state
}
}
I've tried different methods of updating the state (see below) but the state is not updated.
I've commented out the older code which was not working
// return state.map(item=>{
// state.recipeid === recipeid ?
// {...item, newRecipe} : {...item,newRecipe}
// })
return {...state, newRecipe}
Any help would be appreciated.
This is the index.js file from the '../actions' folder
export const TOGGLE = 'TOGGLE'
export const toggleFavId = id => ({
type: 'TOGGLE',
recipeid: id
})
export const IS_FAVOURITE = 'IS_FAVOURITE'
export const isFavourite = id => (
{
type: 'IS_FAVOURITE',
recipeid: id
}
)
export const TOGGLE_FAV = 'TOGGLE_FAV'
export const toggleFav = id => ({
type: 'TOGGLE_FAV',
recipeid: id,
})
this is the VisibleFavicon.js file
import {connect} from 'react-redux'
import Favicon from '../components/favicon'
const mapStateToProps = state =>({
favids: state
})
const mapDispatchToProps = dispatch => ({
toggleFavIds: id => dispatch ({
type: 'TOGGLE',
id
}),
isFavourite : id => dispatch ({
type: 'IS_FAVOURITE',
id
}),
})
export default connect(mapStateToProps, mapDispatchToProps)(Favicon)
Try to get whole state of redux instead of state.favids and wherever you want to use that state you can access it like props.state.favids :
const mapStateToProps = (state) =>({
favids: state,
})
Heres the solution to the issue, this is the code for the reducer.
import { TOGGLE, IS_FAVOURITE } from '../actions'
export const favids = (state = [], action) => {
const { type, recipeid } = action
const newRecipe = {
recipeid,
is_fav: true,
}
switch (type) {
case TOGGLE: {
return state.findIndex(recipe => recipe.recipeid === recipeid) === -1 ?
[...state, newRecipe] :
state.map(recipe =>
recipe.recipeid === recipeid ?
{ ...recipe, is_fav: !recipe.is_fav } : recipe
)
}
default:
return state
}
}

Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method React Native

I'm trying to test a useState value of and object in react native with redux.
I got this error when i have to store a value in state using react-Redux..
I want to store notes and numbers in two arrasy with react native redux and perform both action with single store.Any help is greatly appreciated
Component:
import React, { useState } from 'react'
import { View, StyleSheet } from 'react-native'
import { IconButton, TextInput, FAB } from 'react-native-paper'
import Header from '../components/Header'
function AddNote({ navigation }) {
const [noteTitle, setNoteTitle] = useState('')
const [noteValue, setNoteValue] = useState('')
function onSaveNote() {
navigation.state.params.addNote({ noteTitle, noteValue })
navigation.goBack();
}
return (
<>
<Header titleText='Add a new note' />
<IconButton
icon='close'
size={25}
color='white'
onPress={() => navigation.goBack()}
style={styles.iconButton}
/>
<View style={styles.container}>
<TextInput
label='Add Title Here'
value={noteTitle}
mode='outlined'
onChangeText={setNoteTitle}
style={styles.title}
/>
<TextInput
label='Add Note Here'
value={noteValue}
onChangeText={setNoteValue}
mode='flat'
multiline={true}
style={styles.text}
scrollEnabled={true}
returnKeyType='done'
blurOnSubmit={true}
/>
<FAB
style={styles.fab}
small
icon='check'
disabled={noteTitle == '' ? true : false}
onPress={() => onSaveNote()}
/>
</View>
</>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingHorizontal: 20,
paddingVertical: 20
},
iconButton: {
backgroundColor: 'rgba(46, 113, 102, 0.8)',
position: 'absolute',
right: 0,
top: 40,
margin: 10
},
title: {
fontSize: 24,
marginBottom: 20
},
text: {
height: 300,
fontSize: 16
},
fab: {
position: 'absolute',
margin: 20,
right: 0,
bottom: 0
}
})
export default AddNote
Reducers:
import remove from 'lodash.remove'
// Action Types
export const ADD_NOTE = 'ADD_NOTE'
export const DELETE_NOTE = 'DELETE_NOTE'
export const ADD_NUMBER = 'ADD_NUMBER'
export const DELETE_NUMBER = 'DELETE_NUMBER'
// Action Creators
let noteID = 0
let numberID = 0
export function addnote(note) {
return {
type: ADD_NOTE,
id: noteID++,
note
}
}
export function deletenote(id) {
return {
type: DELETE_NOTE,
payload: id
}
}
export function addnumber(number) {
return {
type: ADD_NUMBER,
id: numberID++,
number
}
}
export function deletenumber(id) {
return {
type: DELETE_NUMBER,
payload: id
}
}
// reducer
const INITIAL_STATE = {
note: [], //note array for save notes
number: [] // number array for save numbers
};
function notesReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_NOTE:
return [
...state,
{
id: action.id,
note: action.note
}
]
case DELETE_NOTE:
const deletedNewArray = remove(state, obj => {
return obj.id != action.payload
})
return deletedNewArray
case ADD_NUMBER:
return [
...state,
{
id: action.id,
number: action.number
}
]
case DELETE_NUMBER:
deletedNewArray = remove(state, obj => {
return obj.id != action.payload
})
return deletedNewArray
default:
return state
}
}
export default notesReducer
So What should i do it..
Please Help Me..
The reducer must return the new state instead of the updated parameter:
// reducer
const INITIAL_STATE = {
note: [], //note array for save notes
number: [] // number array for save numbers
};
function notesReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_NOTE:
return {
...state,
note: [
...state.note,
{
id: action.id,
note: action.note
}
]
};
case DELETE_NOTE:
const note = remove(state.note, obj => obj.id != action.payload);
return {...state, note};
case ADD_NUMBER:
return {
...state,
number: [
...state.number,
{
id: action.id,
number: action.number
}
]
};
case DELETE_NUMBER:
const number = remove(state.number, obj => obj.id != action.payload);
return {...state, number}
default:
return state
}
}

How to change each of state of list item separately in react redux?

Using
react-redux
redux-persist
redux-actions
react-native
I'm learning react-redux and react-native by myself.
I'm trying to update a single item from list in react-redux now.
There's many categories and stores in my project.
An user would select one of categories, and then click 'like button' of one item in store list.
It's like instagram or facebook.
When I change one item's state, the state of every item in the store list change at the same time.
I have no idea why it happens.
I set the structure to ducks pattern to avoid change too much files when to change state.
If anyone give some advice, I would appreciate and it could be helpful for me. Thank you.
I saw some article to resolve this issue, have to give id to distinguish items and make the payload as object. I didn't understand well, so my code is messy now. But I'd like to know what happen to my code, so I share my code.
restaurantContainer.js
class RestaurantListContainer extends Component {
shouldComponentUpdate(nextProps) {
return nextProps.imgUrls !== this.props.imgUrls;
}
componentDidMount() {
const {category, StoreActions} = this.props;
try {
StoreActions.fetchStoreInfo(category);
StoreActions.fetchImgUrl(category);
this.getUid();
} catch (e) {
console.log(e);
}
}
async getUid() {
const {StoreActions} = this.props;
const uid = await storage.getItem('uid');
StoreActions.fetchLikeList(uid);
}
render() {
const {fetching, tabColor, tabName, category, categoryId, navigation, stores, imgUrls, like} = this.props;
const {onClick} = this;
return (
<View>
...
<ScrollView>
{
fetching ?
<View>
<Bars size={30} color="#40D59B"/>
</View>
:
stores.map((store, i) =>
<View key={`item-${i}`}>
<RestaurantItem
key={`restaurantItem-${i}`}
i={i}
category={category}
navigation={navigation}
storeInfo={store}
imgUrls={imgUrls[i]}
categoryId={categoryId}
like={like}
/>
</View>
)
}
</ScrollView>
</View>
);
}
}
export default connect(
({styleMod, storeMod}) => ({
stores: storeMod.stores,
imgUrls: storeMod.imgUrls,
fetching: storeMod.fetching,
likeList: storeMod.likeList
}),
(dispatch) => ({
StoreActions: bindActionCreators(storeActions, dispatch),
})
)(RestaurantListContainer);
restaurantItem.js
class RestaurantItem extends Component {
pressFunc = (item) => {
const {navigation} = this.props;
const {push} = navigation;
console.log(item.name);
push('RestaurantDetail', {info: item});
}
voteAdder = async (storeName) => {
const uid = await storage.getItem('uid');
const {i, categoryId} = this.props;
if (uid) {
const {VoteActions, LikeActions, category, favoriteStores} = this.props;
try {
VoteActions.voteAdd(favoriteStores, category, storeName, uid);
LikeActions.likeClicked(storeName, category, categoryId, i);
} catch (e) {
console.log(e);
}
} else {
alert('You are not authorized!');
}
}
render() {
const {i, storeInfo, category, categoryId, imgUrls, favoriteStores, like} = this.props;
return (
<View style={restaurantCard}>
<StoreImg
img={imgUrls}
name={storeInfo.name}
/>
<StoreInfoBlock
i={i}
storeInfo={storeInfo}
pressFunc={this.pressFunc}
/>
<View style={{flexDirection: 'column'}} >
{
<ThumbImg
voteAdder={() => this.voteAdder(storeInfo.name)}
name={storeInfo.name}
favoriteStore={favoriteStores[category]}
category={category}
like={like}
categoryId={categoryId}
/>
}
<Score count={storeInfo.count}/>
</View>
</View>
);
}
}
export default connect(
({voterMod, likeMod}) => ({
favoriteStores: voterMod.favoriteStores,
like: likeMod.like,
}),
(dispatch) => ({
VoteActions: bindActionCreators(voteActions, dispatch),
LikeActions: bindActionCreators(likeActions, dispatch),
})
)(RestaurantItem);
thumbImg.js
export default class ThumbImg extends Component {
onClick = () => {
this.props.voteAdder();
}
onFlag = () => {
const {like, categoryId, i} = this.props;
if(like.categoryById[categoryId]) {
if(like.storeById[i]) {
console.log(2);
return (
<FastImage
resizeMode={FastImage.resizeMode.cover}
style={{width: 50, height: 50}}
source={require('...')}
/>
);
} else {
return (
<FastImage
resizeMode={FastImage.resizeMode.cover}
style={{width: 50, height: 50}}
source={require('...')}
/>
);
}
} else {
return (
<FastImage
resizeMode={FastImage.resizeMode.cover}
style={{width: 50, height: 50}}
source={require('...')}
/>
);
}
}
render() {
return (
<TouchableOpacity onPress={this.onClick}>
<View style={{paddingTop: 15, paddingRight: 15}}>
{
this.onFlag()
}
</View>
</TouchableOpacity>
);
}
}
likeMod.js
// Action types
const ON_LIKE = 'like/ON_LIKE';
const OFF_LIKE = 'like/OFF_LIKE';
// action creator
export const likeClicked = (store, category, categoryId, i) => (dispatch) => {
const selectedCategory = {categoryById: {}};
const categoryInfo = {
id: categoryId,
name: category,
};
selectedCategory.categoryById[categoryId] = categoryInfo;
const selectedStore = {storeById: {}};
const storeInfo = {
id: i,
name: store
}
selectedStore.storeById[i] = storeInfo;
const favorites = {
...selectedCategory,
...selectedStore
}
dispatch({type: ON_LIKE, payload: favorites});
}
const initialState = {
like: {
categoryById: {},
storeById: {}
}
};
// Reducer
export default handleActions({
[ON_LIKE]: (state, action) => ({...state, like: action.payload}),
[OFF_LIKE]: (state, action) => ({...state, like: action.payload}),
}, initialState);

Normalized data from Redux not displaying in front end (using react)

I have normalized by data in redux, but now grabbing and display it on the front end is causing issues.
Ive been trying to fix this for a few days, i've tried what i feel is the most obvious this.props.... but i'm clearly missing something. Was using Manning newest book on Redux, Redux in Action, which has been a great guide for me so far.
I was trying to break up the data, so the tree would have business (dashboard) and business_locations (another page).
in my Redux DevTools console, the Action Tree looks like:
type: 'RECEIVE_ENTITIES'
payload
entities
business_locations
- 652 {id: 652, business_id: 452...}
business
- 452 {id: 452}
result: 452
my businessReducer:
import {
RECEIVE_ENTITIES,
FETCH_BUSINESS_STARTED,
FETCH_BUSINESS_SUCCESS,
SET_CURRENT_BUSINESS_ID,
} from '../../actions/types';
const initialBusinessState = {
items: [],
isLoading: false,
error: null,
};
export const getBusinesses = state => {
return Object.keys(state.business.items).map(id => {
return state.business.items[id];
});
};
export default function businesses(state = initialBusinessState, action) {
switch (action.type) {
case RECEIVE_ENTITIES: {
const { entities } = action.payload;
if (entities && entities.businesses) {
return {
...state,
isLoading: false,
items: entities.businesses,
};
}
return state;
}
case FETCH_BUSINESS_STARTED: {
return {
...state,
isLoading: true,
};
}
case FETCH_BUSINESS_SUCCESS: {
return {
...state,
isLoading: true,
items: action.payload.businesses,
};
}
default: {
return state;
}
}
}
export function setCurrentBusinessId(id) {
return {
type: SET_CURRENT_BUSINESS_ID,
payload: {
id,
},
};
}
my businessActions;
import { normalize } from 'normalizr';
import {
FETCH_BUSINESS_STARTED,
FETCH_BUSINESS_ERROR,
RECEIVE_ENTITIES,
SET_CURRENT_BUSINESS_ID,
} from './../types';
import * as schema from '../schema';
import * as api from '../../api';
function fetchBusinessStarted() {
return {
type: FETCH_BUSINESS_STARTED,
};
}
function fetchBusinessFailed(err) {
return {
type: FETCH_BUSINESS_ERROR,
payload: {
err,
},
};
}
function receiveEntities(entities) {
return {
type: RECEIVE_ENTITIES,
payload: entities,
};
}
export function setCurrentBusinessId(id) {
return {
type: SET_CURRENT_BUSINESS_ID,
payload: {
id,
},
};
}
export function fetchBusinesses() {
return (dispatch, getState) => {
dispatch(fetchBusinessStarted());
return api
.fetchBusinesses()
.then(resp => {
const businesses = resp.data;
const normalizedData = normalize(businesses, schema.businessSchema);
console.log('normalizedData', normalizedData);
dispatch(receiveEntities(normalizedData));
if (!getState().page.currentBusinessId) {
const defaultBusinessId = sessionStorage.getItem('business_id');
dispatch(setCurrentBusinessId(defaultBusinessId));
}
})
.catch(err => {
console.log(err);
fetchBusinessFailed(err);
});
};
}
my pageReducer
import { SET_CURRENT_BUSINESS_ID } from '../../actions/types';
const InitialPageState = {
currentBusinessId: null,
};
export default function page(state = InitialPageState, action) {
switch (action.type) {
case SET_CURRENT_BUSINESS_ID: {
return {
...state,
currentBusinessId: action.payload.id,
};
}
default: {
return state;
}
}
}
my schema
import { schema } from 'normalizr';
const businessLocationSchema = new schema.Entity('business_locations');
const businessSchema = new schema.Entity('business', {
business_locations: [businessLocationSchema],
});
export { businessSchema };
rootReducer
const rootReducer = (state = {}, action) => {
return {
page: pageReducer(state.page, action),
business: businessReducer(state.businesses, action),
businessLocation: businessLocationsReducer(state.businessLocations,
action),
form: formReducer,
};
};
front end:
class Dashboard extends React.Component {
componentDidMount() {
this.props.dispatch(fetchBusinesses());
}
render() {
if (this.props.isLoading) {
return (
<SpinContainer>
<Spin size="large" />
</SpinContainer>
);
}
console.log(this.props);
return (
<Wrapper>
<Card bordered={false}>
<Maps
zoom={16}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `30vh` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
<p>{this.props.business.website}</p>
<p>{this.props.business.businessName}</p>
</Card>
<Link to="/locations">
<Card bordered={false}>
<h1>****</h1>
</Card>
</Link>
<Link to="stamp-cards">
<Card bordered={false}>
<h1>*****</h1>
</Card>
</Link>
<Card bordered={false}>
<h1>*****</h1>
</Card>
</Wrapper>
);
}
}
function mapStateToProps(state) {
const { isLoading, business } = state.business;
return {
business: getBusinesses(state),
isLoading,
};
}
export default connect(mapStateToProps)(Dashboard);

Resources