When a component is rendered, I'm trying to fetch a list of games and print them on the page in an unordered list. The API call works correctly, and Redux Dev Tools shows the store gets updated, but the component isn't updating to reflect the changes.
Component
import React from 'react';
import { connect } from 'react-redux'
import {fetchAllGames} from "../actions";
class Games extends React.Component {
componentDidMount() {
this.props.dispatch(fetchAllGames());
}
render() {
const { games } = this.props;
return(
<ul>
{ games.map(game => <li key={game.id} >{game.name}</li>) }
</ul>
)
}
}
const mapStateToProps = state => (
{
games: state.games
}
)
const GamesList = connect(
mapStateToProps
)(Games)
export default GamesList;
Actions
import axios from 'axios';
export const fetchGames = (games) => {
return {
type: 'FETCH_GAMES',
games
}
};
export const fetchAllGames = () => {
return (dispatch) => {
return axios.get('/api/games').then(res=> {
dispatch(fetchGames(res.data))
})
.catch(error => {
throw(error);
});
};
};
Store
import {combineReducers, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import GamesList from '../games-list/reducers';
import UsersList from "../users/reducers";
const rootReducer = combineReducers({
'friends' : UsersList,
'games': GamesList
})
const store = createStore(rootReducer, applyMiddleware(thunk));
console.log(store.getState())
export default store
Reducer
const initialState = [
{
id: 0,
name: 'Test Game',
publisher: 'Test Co.'
}
];
const GamesList = (state = initialState, action) => {
switch(action.type){
case 'ADD_GAME':
return [
...state,
{
id: action.id,
name: action.name,
publisher: action.publisher
}
]
case 'DELETE_GAME':
return state.splice(state.indexOf(action.id), 1);
case 'FETCH_GAMES':
return [
...state,
action.games
]
default:
return state
}
}
export default GamesList;
you need to spread your results:
do it like this:
case 'FETCH_GAMES':
return [
...state,
...action.games
]
Related
I am creating a react app with redux for state management, I am facing issues when trying to dispatch and action, action is showing in redux devtools but it's not storing data to redux store not sure why it's happening, very unusual
If anyone knows why this happens please do let me know
My component is below
import axios from "axios";
import React, { Component } from "react";
import { connect } from "react-redux";
import { SETDATA } from "./store";
class Hello extends Component {
constructor() {
super();
this.state = {
data: [],
};
}
componentDidMount() {
this.firstdispatch();
}
firstdispatch = () => {
axios.get("https://jsonplaceholder.typicode.com/users").then((r) => {
console.log("data fetched", r.data);
this.props.setdata(r.data);
});
};
render() {
return (
<div>
{" "}
fff
{/* <button onClick={this.props.setdata}>getdata</button>
<button onClick={this.props.removedata}>decriment</button> */}
{/* <button onClick={props.push}>push</button>
<button onClick={props.pop}>pop</button> */}
{console.log(this.props)}
{this.props.users &&
this.props.users.map((m, i) => (
<div key={i}>
{m.title} {` - - - -`} {m.email}
</div>
))}
</div>
);
}
}
const mapstatetoprops = (state) => {
return {
users: state.users.users || [],
};
};
const mapDispatchTopProps = (dispatch) => {
return {
setdata: (users) => {
dispatch({ type: SETDATA, users });
},
};
};
export default connect(mapstatetoprops, mapDispatchTopProps)(Hello);
Actions reducers and store is below
updated
import * as redux from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
export const SETDATA = "users";
export const DELETEDATA = "data/deletedata";
const initSst = {
users: [],
};
const users = (state = initSst, action) => {
switch (action.type) {
case SETDATA:
return { ...state, ...action.data };
case DELETEDATA:
return { data: null };
default:
return state;
}
};
const rootReducer = redux.combineReducers({
users,
});
const store = redux.createStore(
rootReducer,
composeWithDevTools(
redux.applyMiddleware(thunk)
// other store enhancers if any
)
);
export default store;
Just update "SETDATA" to SETDATA in the switch/case
case SETDATA:
return { ...state, ...action.data };
once I updated the initial state to empty array its working
redux, actions, store
import * as redux from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
export const SETDATA = "users";
export const DELETEDATA = "data/deletedata";
const users = (state = [], action) => {
switch (action.type) {
case SETDATA:
return [...action.payload];
default:
return state;
}
};
const rootReducer = redux.combineReducers({
users: users,
});
const store = redux.createStore(
rootReducer,
composeWithDevTools(
redux.applyMiddleware(thunk)
// other store enhancers if any
)
);
export default store;
component
import axios from "axios";
import React, { Component } from "react";
import { connect } from "react-redux";
import { SETDATA } from "./store";
class Hello extends Component {
constructor() {
super();
this.state = {
data: [],
};
}
componentDidMount() {
this.firstdispatch();
}
firstdispatch = async () => {
await axios.get("https://jsonplaceholder.typicode.com/users").then((r) => {
// console.log("data fetched", r.data);
this.props.setdata(r.data);
});
};
render() {
return (
<div>
fff {console.log(this.props.users, "fff")}
{(this.props.users || []).map((m, i) => (
<div key={i}>
{m.title} {m.email}
</div>
))}
</div>
);
}
}
const mapstatetoprops = (state) => {
return {
users: state.users,
};
};
const mapDispatchTopProps = (dispatch) => {
return {
setdata: (users) => {
dispatch({ type: SETDATA, payload: users });
},
};
};
export default connect(mapstatetoprops, mapDispatchTopProps)(Hello);
How can I add a charging indicator based on the Redux status?
I need to place a loading screen while sending the data.
charging indicator component
import React from 'react';
import { StyleSheet } from 'react-native';
import AnimatedLoader from "react-native-animated-loader";
import {connect} from 'react-redux'
class Loader extends React.Component {
constructor(props) {
super(props);
this.state = {visible: false };
}
// componentDidMount() {
// setInterval(() => {
// this.setState({
// visible: !this.state.visible
// });
// }, 2000);
// }
render() {
const { visible } = this.props;
if (!visible) return outVisible();
return (
<AnimatedLoader
visible={visible}
overlayColor="rgba(255,255,255,0.75)"
source={require("./loader.json")}
animationStyle={styles.lottie}
speed={1}
>
<Text>Carregando...</Text>
</AnimatedLoader>
);
}
}
const styles = StyleSheet.create({
lottie: {
width: 200,
height: 200
}
});
const mapStateToProps = (state) => ({visible: state.visible});
const mapDispatchToProps = dispatch => {
return {outVisible: () => dispatch(setVisible({visible: false}))}
}
export default connect(mapStateToProps,mapDispatchToProps)(Loader)
Action
import { SET_VISIBLE } from './actionsTypes'
export const setVisible = visible => {
return {
type: SET_VISIBLE,
payload: visible
}
}
Reducer
import { SET_VISIBLE } from '../actions/actionsTypes'
const initialState = {
visible: false
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case SET_VISIBLE:
return {
...state,
visible: action.payload.visible
};
default:
return state;
}
}
export default reducer
Store Config
import {
createStore,
combineReducers,
compose,
applyMiddleware
} from 'redux'
import thunk from 'redux-thunk'
import postReducer from './reducers/post'
import userReducer from './reducers/user'
import messageReducer from './reducers/message'
import loadingReducer from './reducers/loading'
const reducers = combineReducers({
user: userReducer,
post: postReducer,
message: messageReducer,
visible: loadingReducer
})
const storeConfig = () => {
return createStore(reducers, compose(applyMiddleware(thunk)))
}
export default storeConfig
actions types
export const USER_LOGGED_IN = 'USER_LOGGED_IN'
export const USER_LOGGED_OUT = 'USER_LOGGED_OUT'
export const SET_MESSAGE = 'SET_MESSAGE'
export const LOADING_USER = 'LOADING_USER'
export const USER_LOADED = 'USER_LOADED'
export const CREATING_POST = 'CREATING_POST'
export const POST_CREATED = 'POST_CREATED'
export const SET_POSTS = 'SET_POSTS'
export const SET_VISIBLE = 'SET_VISIBLE'
app.js
import React, { Component } from 'react'
import { Alert } from 'react-native'
import { connect } from 'react-redux'
import Routes from "./routes";
import { setMessage } from './store/actions/message'
class App extends Component {
componentDidUpdate = () => {
if(this.props.text && this.props.text.toString().trim())
{
Alert.alert(this.props.title || 'Mensagem',this.props.text.toString())
this.props.clearMessage()
}
}
render() {
return (
<Routes />
)
}
}
const mapStateToProps = ({ message}) => {
return {
title: message.title,
text: message.text,
}
}
const mapDispatchToProps = dispatch => {
return {
clearMessage: () => dispatch(setMessage({ title: '', text: '' }))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
Right after the data is sent to the API, I need to return a load indicator to the user, until that data is stored.
Im running into a problem with my redux to firebase connection i believe.
Trying to grab all jobs from users in firebase.
Have my store setup, action and reducer, not really sure where i am going wrong here so i must be overlooking something, nothing is showing up in console and i put a console.log call on my action and nothing shows still.
my action :
// Grab all Jobs
export const getJobs = (jobs) => ({
type: 'GET_JOBS',
jobs
});
export const startGetJobs = () => {
return(dispatch, getState) => {
const uid = getState().auth.uid;
return database.ref(`users/${uid}/jobs`)
.once('value')
.then((snapshot) => {
const jobs =[];
console.log(jobs);
//Parse the data using snapshot
snapshot.forEach((childSnapshot) => {
jobs.push({
id: childSnapshot.key,
...childSnapshot.val()
});
});
dispatch(getJobs(jobs));
});
};
};
my reducer file :
const jobReducerDefaultState = [];
export default (state= jobReducerDefaultState, action) => {
switch(action.type) {
case 'ADD_JOB':
return [
...state,
action.job
];
case 'REMOVE_JOB':
return state.filter(({ id }) => id !== action.id);
case 'EDIT_JOB':
return state.map((job) => {
if(job.id === action.id) {
return {
...job,
...action.updates
};
} else {
return job;
}
});
case 'GET_JOBS':
return action.jobs;
default:
return state;
}
};
my redux store file :
import { createStore, combineReducers, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import jobsReducer from '../reducers/jobs';
import filtersReducer from '../reducers/filters';
import authReducer from '../reducers/auth';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default () => {
const store = createStore(
combineReducers({
jobs: jobsReducer,
filters: filtersReducer,
auth: authReducer
}),
composeEnhancers(applyMiddleware(thunk))
);
return store;
};
And trying to call that with this component :
import React from 'react';
import { connect } from 'react-redux';
import JobDataItem from './JobDataItem';
import { startGetJobs } from '../actions/jobs';
class JobData extends React.Component {
ComponentDidMount() {
this.props.startGetJobs();
}
render() {
return (
<div>
{this.props.jobs.map((job) => {
return <JobDataItem key={job.id} company={job.company}/>
})}
</div>
);
};
};
const mapDispatchToProps = (dispatch) => {
return {
startGetJobs: (jobs) => dispatch(startGetJobs(jobs))
}
}
export default connect(undefined, mapDispatchToProps)(JobData);
which passes that data to the jobDataItem component to render to screen below:
import React from 'react';
import { Link } from 'react-router-dom';
const JobDataItem = ({ id, company}) => (
<div>
<Link to={`/edit/${id}`}>
<h3>{company}</h3>
</Link>
</div>
);
export default JobDataItem;
my firebase db formats like:
users/
user-uid/
jobs/
job-uid/
company:"Company Name",
jobTitle:"jobTitle:,
And so on...
Expected output is "Company Name" but nothing shows up at all. i try to just call props.jobs.length and it shows up as 0 as well.
EDITED
1. “Called startGetJobs in componentDidMount(),
2. “Changed props.jobs.map((job)... to this.props.jobs.map((job)...
I now get props is undefined error in console and nothing still appears on screen.
please help me with a situation around react-redux.
I have issues in updating the state ( which i try to do in a immutable way ), and the component where I use it, never rerenders.
/store/users/index.js
import { USER_LOGIN, USER_LOGOUT} from './actionTypes';
import {
USER_LOGIN,
USER_LOGOUT
} from './actionTypes';
const usersReducer = (user = {}, action) => {
switch(action) {
case USER_LOGIN : /* tried to change id manually, not based on payload, just to see if it works */
return {
...user,
name: 'New user',
isLoggedIn: true
}
case USER_LOGOUT:
return {
...user,
name: 'Anonymous',
isLoggedIn: false
}
default:
return user;
}
}
export default usersReducer;
/store/loops/index.js
import {
LOOPS_ADD
} from './actionTypes';
const loopsReducer = (loops =[], action) => {
switch(action) {
case LOOPS_ADD:
return [
...loops,
action.payload
]
default:
return loops;
}
}
export default loopsReducer;
/store/users/actions.js
import {
USER_LOGIN,
USER_LOGOUT
}
from './actionTypes';
export const userLogin = (newUser) => {
return {
type: USER_LOGIN,
}
}
export const userLogout = () => {
return {
type: USER_LOGOUT
}
}
/store/index.js
import {
createStore,
combineReducers,
applyMiddleware,
compose
} from 'redux';
/* import reducers */
import usersReducer from './users';
import loopsReducer from './loops';
/* import middleware */
import logger from 'redux-logger';
/* initial state */
const initialState = {
user: {
name: 'Anonymous',
isLoggedIn: false,
email: null,
lastLogin: null,
firstTimeLogin: false,
authProvider: 'email',
friendsCount: null
},
loops: []
}
/* reducers */
const rootReducer = combineReducers({
user: usersReducer,
loops: loopsReducer,
});
/* store creation */
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const middleware = composeEnhancers(applyMiddleware(logger));
const store = createStore(
rootReducer,
initialState,
middleware
);
export default store;
/pages/HomeScreen/HomeScreen.js
import React from 'react';
import {connect} from 'react-redux'
import {userLogin} from '../../store/users/actions';
class Home extends React.PureComponent {
render() {
return (
<React.Fragment>
<NavBar>Nav</NavBar>
<Listing>
<Filter>Filter</Filter>
<Card>
<CardAvatar>Avatar</CardAvatar>
<CardBody>Rest of the card</CardBody>
Salut {this.props.name}
<button onClick={() => this.props.login()}>login</button>
</Card>
</Listing>
</React.Fragment>
)
}
}
const mapStateToProps = (state) => {
return {
name: state.user.name
}
}
const mapDispatchToProps = (dispatch) => {
return {
login: () => dispatch(userLogin()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
I don't know if it matters but i'm using styled-components for styling.
I tried removing the combineReducers method, and remain with a single reducer, that did not help.
I tried removing the react-logger middleware, I tried using Immutable.jsbut even if the actions is triggered the redux state does not update, and the Home component doesn't rerender as well.
It seems you are not setting the user on your action:
export const userLogin = (newUser) => {
return {
type: USER_LOGIN,
}
}
Looks like it needs to be:
export const userLogin = (newUser) => {
return {
type: USER_LOGIN,
user: newUser
}
}
Without this there will be no change in state and also no render needed.
Of course, you would then need to change your reducer function so that it is dynamic:
case USER_LOGIN :
return {
...user,
name: action.user.name,
isLoggedIn: true
}
The answer was simple.
I was doing :
const loopsReducer = (loops =[], action) => {
switch(action) {
case LOOPS_ADD:
return [
...loops,
action.payload
]
default:
return loops;
}
}
instead i should have done
const loopsReducer = (loops =[], action) => {
switch(action.type) {
case LOOPS_ADD:
return [
...loops,
action.payload
]
default:
return loops;
}
}
Notice the switch(action) before to switch(action.type)
Sorry for wasting your time, and thank you for all your replies !
**Hello! my problem is my state is not uploading, is always empty altough my actions brings data correct. Can anyone give me some help of what am I doing wrong ?
I think is something with the name or the combine reducers part.
Maybe I am not accesing data correct with my reducer or something like that **
The object I receive from the api call has this format {categories: Array(4), items: Array(50)}
Component
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import ItemList from '../components/ItemList/ItemList';
import { getItems } from './actions'
class ItemListContainer extends PureComponent {
async componentDidMount() {
const { getItems } = this.props;
await getItems()
console.log(this.props)
}
render() {
return <ItemList />;
}
}
const mapStateToProps = state => (
{
items: state.items.items,
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
getItems,
},
dispatch,
);
export default connect(mapStateToProps, mapDispatchToProps)(ItemListContainer);
actions.js
export const GET_ITEMS = 'GET_ITEMS';
export const GET_ITEM = 'GET_ITEM';
export const GET_ITEM_DESCRIPTION = 'GET_ITEM_DESCRIPTION';
export function getItems(query) {
return async function (dispatch) {
// const res = await fetch(`http://localhost:3000/api/items?q=${query}`)
const res = await fetch(`http://localhost:3000/api/items?q=ipad`)
const items = await res.json()
return dispatch({
type: 'GET_ITEMS',
items: items.items,
})
}
}
reducer.js
import { GET_ITEMS } from './actions';
const initialState = {
items: [],
itemsLoaded: false,
};
export default function(state = initialState, action) {
const { type, data } = action;
switch (type) {
case GET_ITEMS:
return {
...state,
items: data,
itemsLoaded: true,
};
default: {
return {
...state
}
}
}
}
I was accessing { data} in the reducer which of course it was empty. The correnct action was items.