I'm trying to use React Redux on my application. I will be building something like instagram, so the scale of the application is going to be big. I have implement redux correctly (I believe) although I'm not getting the fetch result from firestore on the dispatch function, if I insert the same code before the return it works.
action/index.ts:
import { db, auth } from '../../services/firebase';
import { USER_STATE_CHANGE } from '../constants';
export function fetchUser() {
return (dispatch: any) => {
db.collection('users')
.doc(auth.currentUser!.uid)
.get()
.then((snapshot) => {
if (snapshot.exists) {
console.log(snapshot)
dispatch({
type: USER_STATE_CHANGE,
payload: snapshot.data(),
});
}
});
};
}
constants/index.ts:
export const USER_STATE_CHANGE = 'USER_STATE_CHANGE';
reducers/index.ts:
import { combineReducers } from 'redux';
import { user } from './user';
const Reducers = combineReducers({
userState: user,
});
export default Reducers;
reducers/user.ts:
const initialState = {
currentUser: null,
};
export const user = (state = initialState, action: any) => {
return {
...state,
currentUser: action.currentUser,
};
};
App.tsx:
// Redux
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './src/redux/reducers';
import thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default function App() {
if (!fontsLoaded) return <></>;
return (
<ThemeProvider theme={theme}>
<Provider store={store}>
<Main />
</Provider>
<ToastMessage />
</ThemeProvider>
);
}
Main.tsx:
import React, { useEffect, useState } from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { StatusBar } from 'expo-status-bar';
import { AuthRoutes } from './routes/auth.routes';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchUser } from './redux/actions';
import { auth } from './services/firebase';
function Main() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
fetchUser();
auth.onAuthStateChanged((user) => {
if (user) setIsAuthenticated(true);
});
}, []);
return (
<NavigationContainer>
<AuthRoutes isAuthenticated={isAuthenticated} setIsAuthenticated={setIsAuthenticated} />
<StatusBar style="auto" />
</NavigationContainer>
);
}
const mapDispatchProps = (dispatch: any) => bindActionCreators({ fetchUser }, dispatch);
export default connect(null, mapDispatchProps)(Main);
The fetchUser() is called here, and should log the data from firestore, although I don't get any data logged.
The function is beeing called:
on reducer/user.ts
Have you try to do this:
const initialState = {
currentUser: null,
};
export const user = (state = initialState, action: any) => {
return {
...state,
currentUser: action.payload,
};
};
Replace this
export const user = (state = initialState, action: any) => {
return {
...state,
currentUser: action.currentUser,
};
};
With this
export const user = (state = initialState, action: any) => {
return {
...state,
currentUser: action.payload,
};
};
Because you are setting data in payload but you are accessing from currentUser which empty. Either replace payload with currentUser in useDispatch or replace currentUser with payload in reducer.
Related
I am trying to store users fetched by random users api and trying to dispatch it to my store i have store users with an empty array, when i am trying to get users using useSelector i am getting an undefined object.
Here is my store.js:
import { configureStore } from "#reduxjs/toolkit";
import counterReducer from "../features/counter/counterSlice";
import userReducer from "../features/users/userSlice";
export const store = configureStore({
reducer: {
counter: counterReducer,
user: userReducer,
},
});
Here is userSlice.js
import { createSlice } from "#reduxjs/toolkit";
export const userSlice = createSlice({
name: "users",
initialState: {
userArray: [],
},
reducers: {
getUsers: (state, action) => {
state.userArray = action.payload;
}
}
})
export const { getUsers } = userSlice.actions;
export const selectUsers = (state) => state.users.userArray;
export default userSlice.reducer;
Here is App.js
import logo from './logo.svg';
import './App.css';
import {useSelector, useDispatch } from 'react-redux';
import { getUsers, selectUsers } from './features/users/userSlice';
function App() {
const dispatch = useDispatch();
const users = useSelector(selectUsers);
const fetchUsers = async () => {
fetch("https://gorest.co.in/public/v2/users")
.then((response) => response.json())
.then((data) => {
console.log("data=====", data);
dispatch(getUsers(data));
});
};
return (
<div className="App">
<header className="App-header">
<button onClick={fetchUsers}>Get Users</button>
{users.length > 0 &&
users.map((user) => {
<li>user.name</li>;
})}
</header>
</div>
);
}
export default App;
you are mixing up state.user and state.users
either rename user in configureStore to users or use state.user.userArray
I'm getting this weird error in my react-native app. Where I'm using redux to save the user when its is fetched from the firebase database.
Here is the error:
and here is my code in App.js:
import { StatusBar } from 'expo-status-bar';
import React, { useEffect } from 'react';
import { StyleSheet, Text, View, ToastAndroid } from 'react-native';
import firestore from '#react-native-firebase/firestore';
import RNBootSplash from "react-native-bootsplash";
import auth from '#react-native-firebase/auth';
// Navigation
import { NavigationContainer } from '#react-navigation/native';
import BottomTabNavigator from './src/navigation/BottomTabNavigation';
import AuthenticationStack from './src/navigation/AuthenticationStack';
// redux imports
import { Provider } from 'react-redux';
import { saveUserPrefs, saveUser } from './src/redux';
import {store} from './src/redux'
import { connect } from 'react-redux';
const App = (props) => {
const { saveUserPrefs, saveUser } = props;
let isLoggedIn = false;
useEffect(() => {
auth().onAuthStateChanged((user) => {
// if not already login go back to login screen
if(!user){
isLoggedIn = false;
} else {
isLoggedIn = true
RNBootSplash.hide({ fade: true }); // hide the splash screen
ToastAndroid.show("Logged In", ToastAndroid.SHORT);
// save the user & userPrefs in store (redux)
saveUser(user);
saveUserPrefs(user.uid);
}
});
}, [])
return (
<Provider store={store}>
<NavigationContainer>
{isLoggedIn ? <BottomTabNavigator /> : <AuthenticationStack />}
</NavigationContainer>
</Provider>
);
}
const mapStateToProps = (state) => ({
userReducer: state.userReducer
})
export default connect(mapStateToProps, { saveUserPrefs , saveUser})(App);
and here is my redux code:
import axios from 'axios';
import thunk from 'redux-thunk';
import { combineReducers, createStore, applyMiddleware } from 'redux'
import firestore from '#react-native-firebase/firestore';
// Actions
export const saveUserPrefs = (userId) => {
return async (dispatch) => {
try {
console.log('in userlogin function');
const data = await firestore().collection('Users').doc(userId).collection('userPrefs').get();
dispatch({ type: 'SAVE_USER_PREFS', payload: data.docs[0]._data });
} catch (err) {
dispatch({ type: 'ON_ERROR', payload: err });
}
}
}
export const saveUser = (user) => {
return async (dispatch) => {
try {
dispatch({ type: 'SAVE_USER', payload: user})
} catch (err) {
dispatch({ type: 'ON_ERROR', payload: err });
}
}
}
// reducers
const userReducer = (state = {}, action) => {
switch(action.type){
case 'SAVE_USER_PREFS':
return {
...state,
userPrefs: action.payload
}
case 'SAVE_USER':
return {
...state,
user: action.payload
}
case 'ON_ERROR':
return {
...state,
appError: action.payload
}
default:
return state;
}
}
// root reducer
export const rootReducer = combineReducers({
userReducer,
})
// store
export const store = createStore(rootReducer, applyMiddleware(thunk));
I'm new to redux but I read that I have to put the connect method in the component I'm using to get the actions in order to save in the store.
in the App component you cannot connect to the reduxjust wrap your App within another component, that have the Provider
Example code
const AppWrapper = () => {
return (
<Provider store={store}>
<App />
</Provider>
);
};
And remember to delete <Provider store={store}> in your App component
Getting a weird error where 'map' is undefined. I'm not sure if my functions are firing at the wrong time and that's resulting in no data being received.
I'm adding Redux into my simple little application that just pulls data from an API and displays it. It's a list of a bunch of Heroes. Like I said before, I think that the error is coming from different times in the ansyc API call and when Redux is firing. But then again I'm a novice so any help is much appreciated.
import React, {useEffect} from 'react'
import { connect } from 'react-redux'
import { fetchHeroes } from '../actions/heroesActions'
import { Hero } from '../components/Hero'
const HeroesPage = ({ dispatch, loading, heroes, hasErrors }) => {
useEffect(() => {
dispatch(fetchHeroes())
}, [dispatch])
const renderHeroes = () => {
if (loading) return <p>Loading posts...</p>
if (hasErrors) return <p>Unable to display posts.</p>
return heroes.map(hero => <Hero key={hero.id} hero={hero} />)
}
return (
<section>
<h1>Heroes</h1>
{renderHeroes()}
</section>
)
}
// Map Redux state to React component props
const mapStateToProps = state => ({
loading: state.heroes.loading,
heroes: state.heroes.heroes,
hasErrors: state.heroes.hasErrors,
})
export default connect(mapStateToProps)(HeroesPage)
export const GET_HEROES = 'GET HEROES'
export const GET_HEROES_SUCCESS = 'GET_HEROES_SUCCESS'
export const GET_HEROES_FAILURE = 'GET_HEROES_FAILURE'
export const getHeroes = () => ({
type: GET_HEROES,
})
export const getHeroesSuccess = heroes => ({
type: GET_HEROES_SUCCESS,
payload: heroes,
})
export const getHeroesFailure = () => ({
type: GET_HEROES_FAILURE,
})
export function fetchHeroes() {
return async dispatch => {
dispatch(getHeroes())
try {
const response = await fetch('https://api.opendota.com/api/heroStats')
console.log(response)
const data = await response.json()
dispatch(getHeroesSuccess(data))
} catch (error) {
dispatch(getHeroesFailure())
}
}
}
index.js where I created the store
// External imports
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
// Local imports
import App from './App'
import rootReducer from './reducers'
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)))
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
import React, {useEffect} from 'react'
import { useSelector } from 'react-redux'
import { fetchHeroes } from '../actions/heroesActions'
import { Hero } from '../components/Hero'
const HeroesPage = () => {
const data = useSelector(state => state.heroes);
useEffect(() => {
fetchHeroes();
}, [])
const renderHeroes = () => {
if (data.loading) return <p>Loading posts...</p>
if (data.hasErrors) return <p>Unable to display posts.</p>
return data.heroes.map(hero => <Hero key={hero.id} hero={hero} />)
}
return (
<section>
<h1>Heroes</h1>
{renderHeroes()}
</section>
)
}
export default HeroesPage
action file
// import store from your createStore file and access dispatch from it
dispatch = store.dispatch
export const GET_HEROES = 'GET HEROES'
export const GET_HEROES_SUCCESS = 'GET_HEROES_SUCCESS'
export const GET_HEROES_FAILURE = 'GET_HEROES_FAILURE'
export const getHeroes = () => ({
type: GET_HEROES,
})
export const getHeroesSuccess = heroes => ({
type: GET_HEROES_SUCCESS,
payload: heroes,
})
export const getHeroesFailure = () => ({
type: GET_HEROES_FAILURE,
})
export const fetchHeroes = () => {
dispatch(getHeroes())
try {
const response = await fetch('https://api.opendota.com/api/heroStats')
console.log(response)
const data = await response.json()
dispatch(getHeroesSuccess(data))
} catch (error) {
dispatch(getHeroesFailure())
}
}
reducer file
import * as actions from '../actions/heroesActions'
export const initialState = {
heroes: [],
loading: false,
hasErrors: false,
}
export default function heroesReducer(state = initialState, action) {
switch (action.type) {
case actions.GET_HEROES:
return { ...state, loading: true }
case actions.GET_HEROES_SUCCESS:
return { heroes: action.payload, loading: false, hasErrors: false }
case actions.GET_HEROES_FAILURE:
return { ...state, loading: false, hasErrors: true }
default:
return state
}
}
i used react 16+ and redux get jsonplaceholder fake data to assign posts state but not working. can't assign the state. how can i assign json values into state using concat method. i check lifecycle methods also but can't get the answer.
Reducer
import * as actiontypes from './actions';
import axios from 'axios';
const initalstate = {
counter: 0,
posts: []
};
const reducer = (state = initalstate, action ) => {
switch (action.type) {
case actiontypes.actionFetchPost:
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
return {
...state,
posts: state.posts.concat(res.data)
}
});
break;
default :
return state;
}
};
export default reducer;
Redux reducers must be pure functions, it means they should not contain any side effects like calling api.
You need to call api in action creators using redux-thunk package.
Codesandbox
An example action creator:
import {
FETCH_POSTS_STARTED,
FETCH_POSTS_FAILURE,
FETCH_POSTS_SUCCESS
} from "./actionTypes";
import axios from "axios";
export const fetchPosts = () => {
return dispatch => {
dispatch(fetchPostsStarted());
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(res => {
dispatch(fetchPostsSuccess(res.data));
})
.catch(err => {
dispatch(fetchPostsFailed(err.message));
});
};
};
const fetchPostsStarted = () => {
return {
type: FETCH_POSTS_STARTED,
payload: {
isLoading: true
}
};
};
const fetchPostsSuccess = posts => {
return {
type: FETCH_POSTS_SUCCESS,
payload: {
posts
}
};
};
const fetchPostsFailed = error => {
return {
type: FETCH_POSTS_FAILURE,
payload: {
error
}
};
};
And reducer file:
import {
FETCH_POSTS_STARTED,
FETCH_POSTS_SUCCESS,
FETCH_POSTS_FAILURE
} from "../actions/actionTypes";
const initialState = {
posts: [],
loading: false,
error: null
};
export default function(state = initialState, action) {
switch (action.type) {
case FETCH_POSTS_STARTED:
return {
...state,
loading: true
};
case FETCH_POSTS_SUCCESS:
return {
...state,
loading: false,
error: null,
posts: action.payload.posts
};
case FETCH_POSTS_FAILURE:
return {
...state,
loading: false,
error: action.payload.error
};
default:
return state;
}
}
In store we use redux-thunk like this:
import { createStore, compose, applyMiddleware, combineReducers } from "redux";
import reduxThunk from "redux-thunk";
import postsReducers from "./reducers/postsReducers";
const rootReducer = combineReducers({
posts: postsReducers
});
const store = createStore(rootReducer, compose(applyMiddleware(reduxThunk)));
export default store;
Posts component:
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchPosts } from "./store/actions/postsActions";
class Posts extends Component {
componentDidMount() {
this.props.fetchPosts();
}
render() {
const { posts, loading, error } = this.props;
return (
<div>
{loading && <div>LOADING...</div>}
{error && <div>{error}</div>}
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
}
const mapStateToProps = state => {
const { posts, loading, error } = state.posts;
return {
posts,
loading,
error
};
};
export default connect(
mapStateToProps,
{
fetchPosts
}
)(Posts);
Index.js
import ReactDOM from "react-dom";
import store from "./store/store";
import { Provider } from "react-redux";
import Posts from "./Posts";
function App() {
return (
<div className="App">
<Posts />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
Do api call in action and return promise, use redux-thunk and redux-promise-middleware:
export const myApiCall = (args1, arg2) => async (dispatch, getState) => {
const payload = fetch({ ...config });
return dispatch({ type: 'MY_API_CALL', payload });
}
Then in reducer will have to handle two results:
MY_API_CALL_FULFILLED and MY_API_CALL_REJECTED
I want my firebase UI auth to be checked in multiple containers and also redirect to the main page after the authentication is done.
When authentication is done I can see the actions updating and the reducer updating - but then mapstatetoprops does not do anything with the new reducer state
Loginpage that received props and based on that renders
import React from 'react';
import { bindActionCreators } from 'redux'
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
import { Redirect } from 'react-router-dom'
import firebase from 'firebase';
import { connect } from 'react-redux';
import { signIn, signOut } from '../reducer/actions'
import { auth } from '../firebase'
class LoginPage extends React.PureComponent {
// Configure FirebaseUI.
uiConfig = {'FirebaseUI Config'}
componentDidMount = () => {
auth.onAuthStateChanged((user) => { // gets user object on authentication
console.log('OnAuthStateChanged', user)
console.log('Check If Props Change in AuthChange', this.props.isauthed)
if (user) {
this.props.signIn(user)
} else {
this.props.signOut(user)
}
});
}
render() {
console.log('Check If Props Change in Render', this.props.isauthed)
if (!this.props.isauthed) {
return (
<div>
<h1>My App</h1>
<p>Please sign-in:</p>
<StyledFirebaseAuth uiConfig={this.uiConfig} firebaseAuth={firebase.auth()} />
</div>
);
}
return (
<Redirect to='/' />
)
}
}
export default (LoginPage);
JS that should dispatch and update the props
import { connect } from 'react-redux';
import { signIn, signOut } from '../reducer/actions'
import { bindActionCreators } from 'redux'
import LoginPage from './LoginPage';
const mapStateToProps = (state) => {
console.log('LOGINmapstatetoprops', state.Authed)
return {
isauthed: state.Authed.isauthed,
}
}
const mapDispatchToProps = (dispatch) => {
console.log('LOGINmapDISPATCHoprops')
return bindActionCreators({signIn,signOut},dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(LoginPage);
The reducer
import LoginPage from '../components/LoginPage';
import firebase from 'firebase';
const initialState = {
isauthed: false,
error: ''
}
const AuthReducer = (state = initialState, action) => {
console.log('this is an action',action)
switch (action.type) {
case 'IsSignedIn':
return state = [
...state,
{
isauthed: action.payload
}
]
break;
case 'IsNotSignedIn':
return state= [
...state,{
isauthed: action.payload
}]
break;
default: return state
}
}
export default AuthReducer;
This is the actions file
export const signIn = (user) => {
console.log('this is from actions',user)
return {
type: 'isSignedIn',
payload: true
}
}
export const signOut = (user) => {
console.log(user)
return {
type: 'isNotSignedIn',
payload: false
}
}
Any reason why Mapstatetoprops is idle?
I do not think a simple scenario like this needs componentwillreceiveprops method
there is a problem in the reducer, you should return an object and not an array, change to :
case 'IsSignedIn':
return {
...state,
isauthed: action.payload
}