Redux state not updating in function component - javascript

I am working on a signup React app that uses redux. Everything other thing works quite right with the exception of state update.
I've gone through several recommendations already given here and I don't seem to see what's wrong with the code.
The authAction.js
import { API_URL } from '../../../constants/constants';
const LOGIN_SUCCESSFUL = 'LOGIN_SUCCESSFUL';
const LOGIN_LOADING = 'LOGIN_LOADING';
const LOGIN_FAILED = 'LOGIN_FAILED';
const login = values => {
let url = API_URL + 'login';
return async (dispatch) => {
dispatch({
type: LOGIN_LOADING
})
const response = await fetch (url, {
method: 'POST',
body: JSON.stringify(values),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log(data);
if(response.status >=200 && response.status <= 299)
{
sessionStorage.setItem('_token', data.data.jwt)
dispatch({
type: LOGIN_SUCCESSFUL,
payload: {
isAuthenticated: true,
jwt: data.data.jwt ?? ''
}
});
}
dispatch({
type: LOGIN_FAILED,
payload: {
isAuthenticated: false,
jwt: '',
message: data?.message ?? 'Authentication failed.'
}
})
}
}
export { login, logout };
authReducer.js
const LOGIN_SUCCESSFUL = 'LOGIN_SUCCESSFUL';
const LOGIN_FAILED = 'LOGIN_FAILED';
const LOGIN_LOADING = 'LOGIN_LOADING';
const initialState = {
jwt: '',
isAuthenticated: false,
message: '',
loading: false,
error: false,
};
const authReducer = (state = initialState, action) => {
if(action.type === LOGIN_LOADING)
{
return {
...state,
message: 'Authenticating...',
loading: true
}
}
if(action.type === LOGIN_SUCCESSFUL)
{
return {
...state,
isAuthenticated: true,
jwt: action.payload.jwt,
message: action.payload.message,
laoding: false,
error: true
}
}
if(action.type === LOGIN_FAILED)
{
return {
...state,
jwt: '',
isAuthenticated: false,
loading: false
};
}
return initialState;
}
export default authReducer;
rootReducer.js where I combined other reducers
import { combineReducers } from "redux";
import userReducer from "./users/userReducer";
import authReducer from './users/authReducer';
import signupReducer from './users/signupReducer';
import postReducer from './postReducer'
const rootReducer = combineReducers({
user: userReducer,
auth: authReducer,
signup: signupReducer,
posts: postReducer
});
export default rootReducer;
signup.js that handles the view
import {useFormik } from 'formik';
import React, { useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { Link, Navigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import * as Yup from 'yup';
import logo from '../../assets/img/logo1.jpeg';
import Error from '../../components/forms/Error';
import LandingLayout from '../layouts/landing';
import signup from '../../redux/actions/users/signupActions';
import Toast from '../../components/alerts/Toast';
const Signup = () => {
const {loading, error, status} = useSelector(state => state.signup);
const dispatch = useDispatch();
useEffect(()=>{
if(status)
{
setTimeout(() => {
return <Navigate to='/login' />
}, 2000);
}
}, [dispatch, status])
...
onSubmit: (values) => {
dispatch(signup(values));
}
...
export default Signup;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import rootReducer from './redux/reducers/rootReducer';
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
ReactDOM.render(
<React.StrictMode>
<Provider store = {store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
when a log the response from the API call, I get the expected response but nothing is effected on the UI.

Well, it appears that the error was coming from somewhere else. Just as previously stated, everything I did was quite right aside the fact that one of the reducers - userReducer - included in the rootReducer had its action creator returning the wrong payload.
I commented that out and everything else worked.
However, should subtle bug from one reducer affect the entire workings of the store?

Related

Action is dispatched, but state is not updating

I am new to redux, and I have read the other questions concerning this topic. I have tried and looked for quite sometime at this point. I am using redux dev tools in and chrome, and can see my action pulling in the information I need, but it is not going to the state. Here is some of my code, any help would be greatly appreciated.
actions.js
export const FETCH_DATA = {
FETCH_DATA_BEGIN: "FETCH_DATA_BEGIN",
FETCH_DATA_SUCCESS: "FETCH_DATA_SUCCESS",
FETCH_DATA_FAILURE: "FETCH_DATA_FAILURE",
};
export const fetchDataBegin = () => ({
type: FETCH_DATA.FETCH_DATA_BEGIN,
});
export const fetchDataSuccess = (data) => ({
type: FETCH_DATA.FETCH_DATA_SUCCESS,
payload: data,
});
Reducers.js
import { FETCH_DATA } from "./actions";
const initialState = {
data: [],
loading: false,
error: null,
};
export default function displayDataReducer(state = initialState, action) {
switch (action.type) {
case FETCH_DATA.FETCH_DATA_BEGIN:
return {
...state,
loading: true,
error: null,
};
//Sets the data
case FETCH_DATA.FETCH_DATA_SUCCESS:
return {
...state,
loading: false,
data: action.payload.data,
};
my store/index.js
import { createStore, combineReducers, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import displayDataReducer from "./displayData/reducer";
// The Dev Tool extension for the browser
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
// export const RootReducer = combineReducers({
// data: displayDataReducer,
// });
export default createStore(
displayDataReducer,
composeEnhancers(applyMiddleware(thunk))
);
my component
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import Navbar from "../brand/Navbar";
import Masthead from "../brand/Masthead";
import Footer from "../brand/Footer";
import MainContent from "../content/MainContent";
function App() {
const content = useSelector((state) => state);
const dispatch = useDispatch();
function getData() {
return (dispatch) => {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
dispatch({
type: "FETCH_DATA.FETCH_DATA_SUCCESS",
data: res.data,
})
);
};
}
useEffect(() => {
dispatch(getData());
}, []);
Issue: type: "FETCH_DATA.FETCH_DATA_SUCCESS" should just be type: "FETCH_DATA_SUCCESS", or perhaps you didn't mean to include the quotes around it, in which case you also need to import FETCH_DATA.
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import Navbar from "../brand/Navbar";
import Masthead from "../brand/Masthead";
import Footer from "../brand/Footer";
import MainContent from "../content/MainContent";
function App() {
const content = useSelector((state) => state);
const dispatch = useDispatch();
function getData() {
return (dispatch) => {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
dispatch({
type: "FETCH_DATA_SUCCESS", // <-- Drop the prefix
data: res.data,
})
);
};
}
OR
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { FETCH_DATA } from "./actions"; // <-- import actions
import Navbar from "../brand/Navbar";
import Masthead from "../brand/Masthead";
import Footer from "../brand/Footer";
import MainContent from "../content/MainContent";
function App() {
const content = useSelector((state) => state);
const dispatch = useDispatch();
function getData() {
return (dispatch) => {
axios.get("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
dispatch({
type: FETCH_DATA.FETCH_DATA_SUCCESS,
data: res.data,
})
);
};
}

How to dispatch an action and show the data in the app.js using react/redux

I don't know how to load the data of the fetchLatestAnime action in the react app.js file.
My mission is to show the endpoint data that I am doing fetch.
I have already implemented the part of the reducers and action, which you can see in the part below. The only thing I need is to learn how to display the data.
App.js
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
</div>
);
}
export default App;
actions/types.js
export const FETCHING_ANIME_REQUEST = 'FETCHING_ANIME_REQUEST';
export const FETCHING_ANIME_SUCCESS = 'FETCHING_ANIME_SUCCESS';
export const FETCHING_ANIME_FAILURE = 'FETCHING_ANIME_FAILURE';
actions/animesActions.js
import{
FETCHING_ANIME_FAILURE,
FETCHING_ANIME_REQUEST,
FETCHING_ANIME_SUCCESS
} from './types';
import axios from 'axios';
export const fetchingAnimeRequest = () => ({
type: FETCHING_ANIME_REQUEST
});
export const fetchingAnimeSuccess = (json) => ({
type: FETCHING_ANIME_SUCCESS,
payload: json
});
export const fetchingAnimeFailure = (error) => ({
type: FETCHING_ANIME_FAILURE,
payload: error
});
export const fetchLatestAnime = () =>{
return async dispatch =>{
dispatch(fetchingAnimeRequest());
try{
let res = await axios.get('https://animeflv.chrismichael.now.sh/api/v1/latestAnimeAdded');
let json = await res.data;
dispatch(fetchingAnimeSuccess(json));
}catch(error){
dispatch(fetchingAnimeFailure(error));
}
};
};
reducers/latestAnimeReducers.js
import {
FETCHING_ANIME_FAILURE,
FETCHING_ANIME_REQUEST,
FETCHING_ANIME_SUCCESS
} from '../actions/types';
const initialState = {
isFetching: false,
errorMessage: '',
latestAnime: []
};
const latestAnimeReducer = (state = initialState , action) =>{
switch (action.type){
case FETCHING_ANIME_REQUEST:
return{
...state,
isFetching: true,
}
case FETCHING_ANIME_FAILURE:
return{
...state,
isFetching: false,
errorMessage: action.payload
}
case FETCHING_ANIME_SUCCESS:
return{
...state,
isFetching: false,
latestAnime: action.payload
}
default:
return state;
}
};
export default latestAnimeReducer;
reducers/index.js
import latestAnimeReducers from './latestAnimeReducers'
import {combineReducers} from 'redux';
const reducers = combineReducers({
latestAnimeReducers
});
export default reducers;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import resolvers from './redux/reducers/index';
import {createStore , applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
const REDUX_DEV_TOOLS = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(resolvers , REDUX_DEV_TOOLS)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
Ideally, this is how your app.js should look like. I created a working codesandbox for you here. Your initial latestAnime state was an empty array but the action payload you set to it is an object, so remember to pass payload.anime like i have done in the sandbox.
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { fetchLatestAnime } from "./redux/actions/animesActions";
const App = props => {
const { fetchLatestAnime, isFetching, latestAnime, errorMessage } = props;
useEffect(() => {
fetchLatestAnime();
}, [fetchLatestAnime]);
console.log(props);
if (isFetching) {
return <p>Loading</p>;
}
if (!isFetching && latestAnime.length === 0) {
return <p>No animes to show</p>;
}
if (!isFetching && errorMessage.length > 0) {
return <p>{errorMessage}</p>;
}
return (
<div>
{latestAnime.map((anime, index) => {
return <p key={index}>{anime.title}</p>;
})}
</div>
);
};
const mapState = state => {
return {
isFetching: state.latestAnimeReducers.isFetching,
latestAnime: state.latestAnimeReducers.latestAnime,
errorMessage: state.latestAnimeReducers.errorMessage
};
};
const mapDispatch = dispatch => {
return {
fetchLatestAnime: () => dispatch(fetchLatestAnime())
};
};
export default connect(
mapState,
mapDispatch
)(App);

React-Redux Action: 'Dispatch' is not a function

Still getting used to Redux, first off. I have a component that should simply load data for display when the component loads. I have redux setup with the store:
//store.js
import { createStore, applyMiddleware, compose } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import root from './reducers';
const middleware = [thunk, logger];
const initState = {};
const store = createStore(
root,
initState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
and all the reducers that I'll need in a full on combine reducers file:
//{projectFolder}/reducers/index.js
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import errorsReducer from './errorReducer';
import suggestionReducer from './suggestionReducer';
import insiderReducer from './insiderReducer';
import connectionReducer from './connectionReducer';
import outsiderReducer from './outsiderReducer';
import contactReducer from './contactReducer';
import metaReducer from './metaReducer';
export default combineReducers({
auth: authReducer,
errors: errorsReducer,
suggestions: suggestionReducer,
insider: insiderReducer,
connection: connectionReducer,
outsider: outsiderReducer,
contact: contactReducer,
meta: metaReducer
});
The one that I'm interested in is the metaReducer which is the called by an action, or so it should be.
//metaReducer.js
import {GET_INSIDER_META_INFORMATION, GET_OUTSIDER_META_INFORMATION } from '../actions/types';
const initState = {
insider: {},
outsider: {}
};
export default (state = initState, { type, payload }) => {
switch (type) {
case GET_INSIDER_META_INFORMATION:
return{
...state,
insider: payload
}
case GET_OUTSIDER_META_INFORMATION:
return {
...state,
outsider: payload
}
default:
return state;
}
};
The meta reducer is just to house the information coming from the back-end and is each case of the reducer is called from the actions/meta.js file which looks like this:
//{projectfolder}/actions/meta.js
import {
GET_INSIDER_META_INFORMATION,
GET_OUTSIDER_META_INFORMATION,
POPULATE_ERRORS
} from "./types";
import Axios from "axios";
export const getMetaInsider = (dispatch) => {
return Axios.get("meta/insiders")
.then(res =>
dispatch({ type: GET_INSIDER_META_INFORMATION, payload: res.data })
)
.catch(err =>
dispatch({ type: POPULATE_ERRORS, payload: err.response.data })
);
};
export const getMetaOutsider = (dispatch) => {
return Axios.get("meta/outsiders")
.then(res => {
dispatch({ type: GET_OUTSIDER_META_INFORMATION, payload: res.data });
})
.catch(err =>
dispatch({ type: POPULATE_ERRORS, payload: err.response.data })
);
};
and My component that calls all of this is setup as below:
//{projectfolder}/components/home.js
import React, {Component} from 'react';
import {Card, CardTitle, CardSubtitle, CardBody} from 'reactstrap';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {getMetaInsider, getMetaOutsider} from '../actions/meta';
class Home extends Component{
constructor(props){
super(props);
this.state = {
insider:{},
outsider: {}
}
}
componentDidMount() {
console.log(this.props);
this.props.getMetaInsider();
this.props.getMetaOutsider();
}
render(){
let {insiders, outsiders} = this.state;
return(
<React.Fragment>
{*/ omitted as it's not really an issue right now, data is more important than layout /*}
</React.Fragment>
)
}
}
const mapState = state => {
console.log(state);
return {
insider: state.meta.insider,
outsider: state.meta.outsider
}
};
Home.propTypes = {
getMetaInsider: PropTypes.func.isRequired,
getMetaOutsider: PropTypes.func.isRequired,
insider: PropTypes.object.isRequired,
outsider: PropTypes.object.isRequired
};
export default connect(mapState, {getMetaInsider, getMetaOutsider})(Home);
So when the component loads, I get a horribly weird issue where it looks like jquery is being called, and it's imported in my App.js file for bootstrap. However, the main error is this:
"TypeError: dispatch is not a function
at http://localhost:3000/static/js/bundle.js:73524:22"
Which maps up to the .catch block of the getMetaInsider function.
You have to do something like this:
export const getMetaOutsider = () => {
return (dispatch) => {
Axios.get("meta/outsiders")
.then(res => {
dispatch({ type: GET_OUTSIDER_META_INFORMATION, payload: res.data });
})
.catch(err =>
dispatch({ type: POPULATE_ERRORS, payload: err.response.data })
);
}
};
Try this, It should work. Feedbacks are welcome.
redux-thunk handles functions passed as the argument to dispatch instead of objects.

React + Redux binded state has no data

After one of the Redux tutorials decided to implement that facny action->reducer->store->view chain for simple app with only login part.
Seems like all setted up but when I run my app - in mapStateToProps(currentState) no any sign of the any custom state fields which I expected to see! (default state from reducer). But the action function is fine, as you can see on the screenshot
I can't see whats wrong here so, decided to ask it.
So here is the code
So, first of all - store.js
import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, applyMiddleware(thunk));
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
then login reducer
const initialState = {
user: {
name: '',
password: ''
},
fetching: false
}
export default function login(state = initialState, action) {
switch (action.type) {
case LOGIN_REQUEST: {
return { ...state, fetching: true }
}
case LOGIN_SUCCESS: {
return { ...state, user: action.data, fetching: false }
}
case LOGIN_FAIL: {
return { ...state, user: -1, fetching: false }
}
default: {
return state;
}
}
}
and the root (reducers/index.js):
import login from './login/login';
import { combineReducers } from 'redux'
export default combineReducers({
login
});
the action
import {
LOGIN_REQUEST,
LOGIN_SUCCESS,
LOGIN_FAIL
} from '../../constants/login.js';
export function onLoginAttempt(userData) {
return (dispatch) => {
dispatch({
type: LOGIN_REQUEST,
user: userData
})
tryLogin(userData);
}
};
function tryLogin(userData) {
let url = 'SignIn/Login ';
return (dispatch) => {
axios.post(url, userData)
.then((response) => dispatch({
type: LOGIN_SUCCESS,
data: response.data
})).error((response) => dispatch({
type: LOGIN_FAIL,
error: response.error
}))
}
};
So here is entrance point:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './containers/app.js';
import configureStore from './store/configureStore';
let store = createStore(configureStore);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("content")
);
and here is the app.js (Login is just sompe custom div with two fields nothing special)
import React, { Component } from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import Login from '../components/login/Login';
import * as pageActions from '../actions/login/login'
class App extends Component {
render() {
const { user, fetching } = this.props;
const { onLoginAttempt } = this.props.pageActions;
return <div>
<Login name={user.name} password={user.password} fetching={fetching} onLoginAttempt={onLoginAttempt} />
</div>
}
}
function mapStateToProps(currentState) {
return {
user: currentState.user,
fetching: currentState.fetching
}
}
function mapDispatchToProps(dispatch) {
return {
pageActions: bindActionCreators(pageActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
I see that you have state which looks like:
reduxState = {
login: {
user: {
name: '',
password: ''
},
fetching: false
}
}
but then you try to access properties that don't exist.
function mapStateToProps(currentState) {
return {
user: currentState.user,
fetching: currentState.fetching
}
}
I think you need to:
function mapStateToProps(currentState) {
return {
user: currentState.login.user,
fetching: currentState.login.fetching
}
}
You have this line let store = createStore(configureStore); on your entry point. However, inside configureStore, you have a call to createStore()
Basically you're calling something like createStore(createStore(reducers)). That's probably the cause of the problem.
You should probably call it like
let store = configureStore( /* pass the initial state */ )

Error with redux-promise : Actions must be plain objects. Use custom middleware

I'm actually trying to use redux-promise, and when i send a request to my api in my action, i get this error.
I saw that there was a speaking subject to the same error but I have not found my problem solving in responses.
So this is my code :
./app.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import { Router, browserHistory } from 'react-router'
import reducers from './reducers/app-reducer'
import routes from './routes'
import promise from 'redux-promise'
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>, document.querySelector('.container'))
./reducers/app-reducer.js
import { combineReducers } from 'redux'
import user from './user-reducer'
const rootReducer = combineReducers({
user: user
})
export default rootReducer
action whose called :
./actions/user-actions.js
import axios from 'axios'
export const UPDATE_TOKEN = 'UPDATE_TOKEN'
export const CREATE_SESSION = 'CREATE_SESSION'
export const CREATE_SESSION_ERROR = 'CREATE_SESSION_ERROR'
export function createSession(obj){
if (typeof obj === 'string') {
return {
type: UPDATE_TOKEN,
payload: obj
}
}
else {
axios.post('http://localhost:8080' + '/session', {
data: {'Email': obj.email, 'Password': obj.password},
headers: {'Content-Type': 'application/json'}
}).then((response) => {
return {
type: CREATE_SESSION,
payload: response.data
}
}).catch((error) => {
return {
type: CREATE_SESSION_ERROR,
payload: error
}
})
}
}
I've also tried with redux-thunk, I get the same error.
Someone you have an idea ? or maybe do I take me wrong?
Thanks
When creating ajax calls in actions, you should use redux-thunk and compose.
import {createStore, applyMiddleware, compose} from "redux";
import thunk from 'redux-thunk';
Change your store like this:
const createStoreWithMiddleware = compose(applyMiddleware(thunk))(createStore)(reducers);
And set axios to use dispatch:
return (dispatch) => {
axios.post('http://localhost:8080' + '/session', {
data: {'Email': obj.email, 'Password': obj.password},
headers: {'Content-Type': 'application/json'}
}).then((response) => {
dispatch ({
type: CREATE_SESSION,
payload: response.data
})
}).catch((error) => {
return {
type: CREATE_SESSION_ERROR,
payload: error
}
})
}

Categories