How to rehydrate my apollo state from server side? - javascript

I am totally new to react-apollo I am pretty confused that how to rehydrate state from the server side to client And my app is working, But the problem is it is not using preloaded state from Apollo After component rendered it is calling the API again.
Seriously Redux Integration Makes Complicated only Apollo state is rendering not the custom redux state that's the problem here.But I don;t know how to integrate.
Server.js
const HTML = ({ html,state}) => (
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta httpEquiv="Content-Language" content="en" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div
id="app"
dangerouslySetInnerHTML={{ __html: html }} />
<script dangerouslySetInnerHTML={{
__html: `window.__STATE__=${JSON.stringify(state)};`,
}} />
<script src="/static/app.js" />
</body>
</html>
);
app.get('/*',(req,res) => {
const routeContext = {};
const client = serverClient();
const components = (
<StaticRouter location={req.url} context={routeContext}>
<ApolloProvider store={store} client={client}>
<WApp />
</ApolloProvider>
</StaticRouter>
);
getDataFromTree(components).then(() => {
const html = ReactDOMServer.renderToString(components);
const initialState = {apollo: client.getInitialState()}
res.send(`<!DOCTYPE html>\n${ReactDOMServer.renderToStaticMarkup(
<HTML
html={html}
state={initialState}
/>,
)}`)
})
})
apolloClient.js
import ApolloClient, {
createNetworkInterface,
addTypeName,
} from 'apollo-client';
const isProduction = process.env.NODE_ENV !== 'development';
const testUrl = 'http://localhost:3000/api';
// const url = isProduction ? productionUrl : testUrl;
const url = testUrl;
const client = new ApolloClient({
networkInterface: createNetworkInterface({uri:testUrl}),
dataIdFromObject:({id}) => id,
reduxRootKey:state => state.apollo,
initialState: (typeof window !=='undefined')? window.__STATE__:{}
});
export default client;
store.js
import { createStore, compose, applyMiddleware } from 'redux';
import { syncHistoryWithStore } from 'react-router-redux';
import thunk from 'redux-thunk';
import {createLogger} from 'redux-logger';
import client from '../apolloClient';
import rootReducer from '../Reducers'
//All Reducer
import {initialState as allPosts} from '../Reducers/AllPosts_Reucer';
const isProduction = process.env.NODE_ENV !== 'development';
const isClient = typeof document !== 'undefined';
const initialState = {
allPosts
};
const middlewares = [thunk, client.middleware()];
const enhancers = [];
if (!isProduction && isClient) {
const loggerMiddleware = createLogger();
middlewares.push(loggerMiddleware);
if (typeof devToolsExtension === 'function') {
const devToolsExtension = window.devToolsExtension;
enhancers.push(devToolsExtension());
}
}
const composedEnhancers = compose(
applyMiddleware(...middlewares),
...enhancers
);
const store = createStore(
rootReducer,
initialState,
composedEnhancers,
);
export default store;
Sample Component
import React,{Component} from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import * as postActions from '../../Redux/Actions/postActions';
class Home extends Component{
componentWillMount(){
// console.log('From Will Mount',this.props.posts)
}
renderAllPost(){
const {loading,posts} = this.props;
if(!loading){
return posts.map(data => {
return <li key={data.id}>{data.title}</li>
})
}else{
return <div>loading</div>
}
}
render(){
console.log(this.props);
return(
<div>
{this.renderAllPost()}
</div>
)
}
}
//start from here
const GetallPosts = gql`
query getAllPosts{
posts{
id
title
body
}
}
`;
// const mapStateToPros = (state) => ({
// allPosts:state.allPosts
// });
const mapDispatchToProps = (dispatch) => ({
actions:bindActionCreators(
postActions,
dispatch
)
});
const ContainerWithData = graphql(GetallPosts,{
props:({ data:{loading,posts} }) => ({
posts,
loading,
})
})(Home)
export default connect(
// mapStateToPros,
// mapDispatchToProps
)(ContainerWithData)

You can inject the redux-persist state directly into apollo-client with
getStoredState({ storage: localforage }, (err, rehydratedState) => { ... }
also i wish there was a different approach, check for Delay Render Until Rehydration Complete

Related

TypeError: searchField.toLowerCase is not a function when using hooks an redux

I am have been working on a little project to better understand react. I recently converted it to use hooks and I am trying to implement redux, with it. However I get the following error now.
TypeError: searchField.toLowerCase is not a function
looking at the docs, I stopped using connect from react-redux and switched to using useDispatch and useSelector. But I believe I have set up everything correctly but not sure as to why this error being raise.
This is my action.js
import { SEARCH_EVENT } from './searchfield_constants';
export const setSearchField = (payload) => ({ type: SEARCH_EVENT, payload });
This is my reducer
import { SEARCH_EVENT } from './searchfield_constants';
const initialState = {
searchField: '',
};
export const searchRobots = (state = initialState, action = {}) => {
switch (action.type) {
case SEARCH_EVENT:
return { ...state, searchField: action.payload };
default:
return state;
}
};
this is my index.js where I am using the Provider from react-redux
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { searchRobots } from './searchfield/searchfield_reducers';
import './styles/index.css';
import App from './App';
const store = createStore(searchRobots);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
finally here is my App.jsx
import { useState, useEffect, useCallback } from 'react';
import { setSearchField } from './searchfield/searchfield_actions';
import { useDispatch, useSelector } from 'react-redux';
import axios from 'axios';
import React from 'react';
import CardList from './components/CardList';
import SearchBox from './components/SearchBox';
import Scroll from './components/Scroll';
import Error from './components/Error';
import 'tachyons';
import './styles/App.css';
// const mapStateToProps = (state) => ({
// searchField: state.searchField,
// });
// const mapDispatchToProps = (dispatch) => ({
// onSearchChange: (e) => dispatch(setSearchField(e.target.value)),
// });
const App = () => {
const searchField = useSelector(state => state.searchField)
const dispatch = useDispatch();
const [robots, setRobots] = useState([]);
// const [searchField, setSearchField] = useState('');
const fetchUsers = useCallback(async () => {
try {
const result = await axios('//jsonplaceholder.typicode.com/users');
setRobots(result.data);
} catch (error) {
console.log(error);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
fetchUsers();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const filteredRobots = robots.filter((robot) => {
return robot.name.toLowerCase().includes(searchField.toLowerCase());
});
return !robots.length ? (
<h1 className='f1 tc'>Loading...</h1>
) : (
<div className='App tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={dispatch(setSearchField(e => e.target.value))} />
<Scroll>
<Error>
<CardList robots={filteredRobots} />
</Error>
</Scroll>
</div>
);
};
export default App;
what am I doing wrong?
So the solution was the following,
I created a function called on searchChange, which calls dispatch and then the setSearchField which uses the e.target.value as the payload.
const onSearchChange = (e) => {
dispatch(setSearchField(e.target.value));
};
so the final return looks like the following
return !robots.length ? (
<h1 className='f1 tc'>Loading...</h1>
) : (
<div className='App tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={onSearchChange} />
<Scroll>
<Error>
<CardList robots={filteredRobots} />
</Error>
</Scroll>
</div>
);
};
In you App.js, convert this line
const searchField = useSelector(state => state.searchField)
to
const { searchField } = useSelector(state => state.searchField)
basically de-structure out searchField from state.searchField
This is attributed to the fact how redux sets state.
In your reducer searchRobots the initial state provided by redux will be
state = {
...state,
searchField
}
and in this line return { ...state, searchField: action.payload };, you're adding
another property searchField to state.searchField object so you'll need to de-structure it out.
It looks like your searchField value is getting set to undefined or some non-string value.
I found this line to be incorrect
<SearchBox searchChange={dispatch(setSearchField(e => e.target.value))} />
It should be changed to
<SearchBox searchChange={() => dispatch(setSearchField(e => e.target.value))} />
So that on search change this function can be called. Currently you are directly calling dispatch and this may be setting your searchField to undefined
Also for safer side before using toLowerCase() convert it to string ie searchField.toString().toLowerCase()

Why does React/redux state reset on refresh?

When i login, everything works fine but the moment i hit refresh or navigate somewhere else, the state gets reset. Any idea why? I want to be able to reference the user from the state and get info like name etc and use it inside components. But it only works right after i login and then it will reset.
also, why do i have to use .get in mapstatetoprops? If not i get a Map object. is it because of IMMUTABLE.JS?
Here's my app.js file
/**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import '#babel/polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router/immutable';
import jwt_decode from 'jwt-decode';
import FontFaceObserver from 'fontfaceobserver';
import history from 'utils/history';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
import './styles/layout/base.scss';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
import { setCurrentUser, logoutUser } from './redux/actions/authActions';
import setAuthToken from './utils/setAuthToken';
// Load the favicon and the .htaccess file
import '!file-loader?name=[name].[ext]!../public/favicons/favicon.ico'; // eslint-disable-line
import 'file-loader?name=.htaccess!./.htaccess'; // eslint-disable-line
import configureStore from './redux/configureStore';
// Import i18n messages
import { translationMessages } from './i18n';
// Check for token to keep user logged in
if (localStorage.jwtToken) {
// Set auth token header auth
const token = JSON.parse(localStorage.jwtToken);
setAuthToken(token);
// Decode token and get user info and exp
const decoded = jwt_decode(token);
console.log(decoded);
// Set user and isAuthenticated
setCurrentUser(decoded);
// Check for expired token
const currentTime = Date.now() / 1000; // to get in milliseconds
if (decoded.exp < currentTime) {
// Logout user
logoutUser();
// Redirect to login
window.location.href = './';
}
}
// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});
// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
document.body.classList.add('fontLoaded');
});
// Create redux store with history
const initialState = {};
const store = configureStore(initialState, history);
const MOUNT_NODE = document.getElementById('app');
const render = messages => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</LanguageProvider>
</Provider>,
MOUNT_NODE,
);
};
if (module.hot) {
// Hot reloadable React components and translation json files
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept(['./i18n', 'containers/App'], () => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
new Promise(resolve => {
resolve(import('intl'));
})
.then(() =>
Promise.all([import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js')]),
) // eslint-disable-line prettier/prettier
.then(() => render(translationMessages))
.catch(err => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
index.js inside app folder
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import NotFound from 'containers/Pages/Standalone/NotFoundDedicated';
import Auth from './Auth';
import Application from './Application';
import ThemeWrapper, { AppContext } from './ThemeWrapper';
import { Login } from '../pageListAsync';
import PrivateRoute from './PrivateRoute';
const isLoggedIn = localStorage.getItem('jwtToken') !== null ? true : false;
window.__MUI_USE_NEXT_TYPOGRAPHY_VARIANTS__ = true;
console.log(localStorage);
class App extends React.Component {
render() {
return (
<ThemeWrapper>
<AppContext.Consumer>
{changeMode => (
<Switch>
<Route path="/" exact component={Login} />
<PrivateRoute isLoggedIn={isLoggedIn} exact path="/app" component={Application} />
<Route
path="/app"
render={props => <Application {...props} changeMode={changeMode} />}
/>
<Route component={Auth} />
<Route component={NotFound} />
</Switch>
)}
</AppContext.Consumer>
</ThemeWrapper>
);
}
}
export default App;
authactions.js that will setcurrentuser but it only happens once it seems and not again once i reload.
import axios from 'axios';
import jwt_decode from 'jwt-decode';
import setAuthToken from '../../utils/setAuthToken';
import { GET_ERRORS, SET_CURRENT_USER, USER_LOADING } from '../constants/authConstants';
// Login - get user token
export const loginUser = userData => dispatch => {
axios
.post('/api/total/users/login', userData)
.then(res => {
// Save to localStorage
// Set token to localStorage
const { token } = res.data;
localStorage.setItem('jwtToken', JSON.stringify(token));
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
console.log('logged');
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data,
}),
);
};
// Set logged in user
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded,
};
};
// User loading
export const setUserLoading = () => {
return {
type: USER_LOADING,
};
};
// Log user out
export const logoutUser = history => dispatch => {
// Remove token from local storage
localStorage.removeItem('jwtToken);
// Remove auth header for future requests
setAuthToken(false);
// Set current user to empty object {} which will set isAuthenticated to false
dispatch(setCurrentUser({}));
// history.push('/app');
};
EDIT: When i look at redux devtools i see that the IF block does run every time it is refreshed, but the correct state doesn't seem to be passed on to the other components. The other components get the correct state the first time (isAuthenticated: true) but once i refresh, they go back to false. In redux devtools i see this every time i refresh.
main reducer
/**
* Combine all reducers in this file and export the combined reducers.
*/
import { reducer as form } from 'redux-form/immutable';
import { combineReducers } from 'redux-immutable';
import { connectRouter } from 'connected-react-router/immutable';
import history from 'utils/history';
import languageProviderReducer from 'containers/LanguageProvider/reducer';
import uiReducer from './modules/ui';
import initval from './modules/initForm';
import login from './modules/login';
import treeTable from '../containers/Tables/reducers/treeTbReducer';
import crudTable from '../containers/Tables/reducers/crudTbReducer';
import crudTableForm from '../containers/Tables/reducers/crudTbFrmReducer';
import ecommerce from '../containers/SampleApps/Ecommerce/reducers/ecommerceReducer';
import contact from '../containers/SampleApps/Contact/reducers/contactReducer';
import chat from '../containers/SampleApps/Chat/reducers/chatReducer';
import email from '../containers/SampleApps/Email/reducers/emailReducer';
import calendar from '../containers/SampleApps/Calendar/reducers/calendarReducer';
import socmed from '../containers/SampleApps/Timeline/reducers/timelineReducer';
import taskboard from '../containers/SampleApps/TaskBoard/reducers/taskboardReducer';
/**
* Branching reducers to use one reducer for many components
*/
function branchReducer(reducerFunction, reducerName) {
return (state, action) => {
const { branch } = action;
const isInitializationCall = state === undefined;
if (branch !== reducerName && !isInitializationCall) {
return state;
}
return reducerFunction(state, action);
};
}
/**
* Merges the main reducer with the router state and dynamically injected reducers
*/
export default function createReducer(injectedReducers = {}) {
const rootReducer = combineReducers({
form,
ui: uiReducer,
initval,
login,
socmed,
calendar,
ecommerce,
contact,
chat,
email,
taskboard,
treeTableArrow: branchReducer(treeTable, 'treeTableArrow'),
treeTablePM: branchReducer(treeTable, 'treeTablePM'),
crudTableDemo: branchReducer(crudTable, 'crudTableDemo'),
crudTableForm,
crudTbFrmDemo: branchReducer(crudTableForm, 'crudTbFrmDemo'),
language: languageProviderReducer,
router: connectRouter(history),
...injectedReducers,
});
// Wrap the root reducer and return a new root reducer with router state
const mergeWithRouterState = connectRouter(history);
return mergeWithRouterState(rootReducer);
}
createStore.js
/**
* Create the store with dynamic reducers
*/
import { createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import { fromJS } from 'immutable';
import createSagaMiddleware from 'redux-saga';
import thunk from 'redux-thunk';
import createReducer from './reducers';
export default function configureStore(initialState = {}, history) {
let composeEnhancers = compose;
const reduxSagaMonitorOptions = {};
// If Redux Dev Tools and Saga Dev Tools Extensions are installed, enable them
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production' && typeof window === 'object') {
/* eslint-disable no-underscore-dangle */
if (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true });
}
// NOTE: Uncomment the code below to restore support for Redux Saga
// Dev Tools once it supports redux-saga version 1.x.x
if (window.__SAGA_MONITOR_EXTENSION__)
reduxSagaMonitorOptions = {
sagaMonitor: window.__SAGA_MONITOR_EXTENSION__,
};
/* eslint-enable */
}
const sagaMiddleware = createSagaMiddleware(reduxSagaMonitorOptions);
// Create the store with two middlewares
// 1. sagaMiddleware: Makes redux-sagas work
// 2. routerMiddleware: Syncs the location/URL path to the state
const middleware = [thunk];
const middlewares = [...middleware, sagaMiddleware, routerMiddleware(history)];
const enhancers = [applyMiddleware(...middlewares)];
const store = createStore(createReducer(), fromJS(initialState), composeEnhancers(...enhancers));
// Extensions
store.runSaga = sagaMiddleware.run;
store.injectedReducers = {}; // Reducer registry
store.injectedSagas = {}; // Saga registry
// Make reducers hot reloadable, see http://mxs.is/googmo
/* istanbul ignore next */
if (module.hot) {
module.hot.accept('./reducers', () => {
store.replaceReducer(createReducer(store.injectedReducers));
});
}
return store;
}
the main app file
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import NotFound from 'containers/Pages/Standalone/NotFoundDedicated';
import jwtDecode from 'jwt-decode';
import configureStore from '../../redux/configureStore';
import { setCurrentUser, logoutUser } from '../../redux/actions/authActions';
import setAuthToken from '../../utils/setAuthToken';
import Auth from './Auth';
import Application from './Application';
import ThemeWrapper, { AppContext } from './ThemeWrapper';
import { PrivateRoute } from './PrivateRoute';
window.__MUI_USE_NEXT_TYPOGRAPHY_VARIANTS__ = true;
const initialState = {};
const store = configureStore(initialState);
const auth = localStorage.jwtToken ? true : false;
// Check for token to keep user logged in
if (localStorage.jwtToken) {
// Set auth token header auth
const token = JSON.parse(localStorage.jwtToken);
setAuthToken(token);
// Decode token and get user info and exp
const decoded = jwtDecode(token);
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
// Check for expired token
const currentTime = Date.now() / 1000; // to get in milliseconds
if (decoded.exp < currentTime) {
// Logout user
logoutUser();
// Redirect to login
window.location.href = './';
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
errors: {},
};
}
render() {
return (
<ThemeWrapper>
<AppContext.Consumer>
{changeMode => (
<Switch>
{/* <Route path="/" exact component={Login} /> */}
<PrivateRoute
path="/app"
auth={auth}
component={props => <Application {...props} changeMode={changeMode} />}
/>
<Route component={Auth} />
<Route component={NotFound} />
</Switch>
)}
</AppContext.Consumer>
</ThemeWrapper>
);
}
}
export default App;
infectreducer
import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { ReactReduxContext } from 'react-redux';
import getInjectors from './reducerInjectors';
/**
* Dynamically injects a reducer
*
* #param {string} key A key of the reducer
* #param {function} reducer A reducer that will be injected
*
*/
export default ({ key, reducer }) => WrappedComponent => {
class ReducerInjector extends React.Component {
static WrappedComponent = WrappedComponent;
static contextType = ReactReduxContext;
static displayName = `withReducer(${WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'})`;
constructor(props, context) {
super(props, context);
getInjectors(context.store).injectReducer(key, reducer);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistNonReactStatics(ReducerInjector, WrappedComponent);
};
const useInjectReducer = ({ key, reducer }) => {
const context = React.useContext(ReactReduxContext);
React.useEffect(() => {
getInjectors(context.store).injectReducer(key, reducer);
}, []);
};
export { useInjectReducer };
reducerinjector
import invariant from 'invariant';
import { isEmpty, isFunction, isString } from 'lodash';
import checkStore from './checkStore';
import createReducer from '../redux/reducers';
export function injectReducerFactory(store, isValid) {
return function injectReducer(key, reducer) {
if (!isValid) checkStore(store);
invariant(
isString(key) && !isEmpty(key) && isFunction(reducer),
'(app/utils...) injectReducer: Expected `reducer` to be a reducer function',
);
// Check `store.injectedReducers[key] === reducer` for hot reloading when a key is the same but a reducer is different
if (
Reflect.has(store.injectedReducers, key)
&& store.injectedReducers[key] === reducer
) return;
store.injectedReducers[key] = reducer; // eslint-disable-line no-param-reassign
store.replaceReducer(createReducer(store.injectedReducers));
};
}
export default function getInjectors(store) {
checkStore(store);
return {
injectReducer: injectReducerFactory(store, true),
};
}
Use persistedState. This is index.js file example
function saveToLocalStorage(state) {
try {
const serializedState = JSON.stringify(state)
localStorage.setItem('state', serializedState)
} catch (err) {
console.log(err)
}
}
function loadFromLocalStorage() {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) return undefined;
return JSON.parse(serializedState)
} catch (err) {
console.log(err)
return undefined;
}
}
const persistedState = loadFromLocalStorage();
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
reducer,
persistedState,
applyMiddleware(logger, sagaMiddleware))
sagaMiddleware.run(watchLoadData);
store.subscribe(() => saveToLocalStorage(store.getState()))
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter>,
document.getElementById('root')
);

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);

what is this error message for ? Actions must be plain objects. Use custom middleware for async actions

actionTypes.js
export const ADD_INGREDIENT = 'ADD_INGREDIENT';
export const REMOVE_INGREDIENT = 'REMOVE_INGREDIENT';
export const SET_INGREDIENTS = 'SET_INGREDIENTS';
export const FETCH_INGREDIENTS_FAILED = 'FETCH_INGREDIENTS_FAILED';
burgerBuilder.js /actions
export const setIngredients = (ingredients) => {
return {
type: actionTypes.SET_INGREDIENTS,
ingredients: ingredients
};
};
export const fetchIngredientsFailed = () => {
return {
type: actionTypes.FETCH_INGREDIENTS_FAILED
};
};
export const initIngredients = () => {
return dispatch => {
axios.get('/ingredients.json')
.then(response => {
dispatch(setIngredients(response.data))
})
.catch(error => {
dispatch(fetchIngredientsFailed())
});
};
};
burgerBuilder.js /reducer
case actionTypes.SET_INGREDIENTS:
return {
...state,
ingredients: action.ingredients,
error: false
};
case actionTypes.FETCH_INGREDIENTS_FAILED:
return {
...state,
error: true
};
BurgerBuilder.js/containers
componentDidMount () {
this.props.onInitIngredients();
}
//Some Code...
const mapStateToProps = state => {
return {
ings: state.ingredients,
price: state.totalPrice,
error: state.error
}
};
const mapDispatchToProps = dispatch => {
return {
onIngredientAdded: (ingName) => dispatch(burgerbuilderActions.addIngredient(ingName)),
onIngredientRemoved: (ingName) => dispatch(burgerbuilderActions.removeIngredient(ingName)),
onInitIngredients: () => dispatch(burgerbuilderActions.initIngredients())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(BurgerBuilder, axios));
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import {BrowserRouter} from 'react-router-dom';
import thunk from 'redux-thunk';
import burgerBuilderReducer from './store/reducers/burgerBuilder';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION__ || compose;
const store = createStore(burgerBuilderReducer, composeEnhancers(
applyMiddleware(thunk)
));
const app = (
<Provider store={store}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
);
I've got this error "Actions must be plain objects. Use custom middleware for async actions" when I was working on a demo project. I don't know but I feel that this error comes from initIngredients() in burgerBuilder.js/action file.
I'm new in react!
It seems that the code is currently broken,
you can fix this issue by change:
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION__ || compose;
const store = createStore(burgerBuilderReducer, composeEnhancers(
applyMiddleware(thunk)
));
with:
const store = createStore(
rootReducer,
//composeEnhancers(applyMiddleware(thunk)) // => NOTE: This would break the code!
// Thisone instead will work fine...
compose(
applyMiddleware(
thunk
// Other middlewares
),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() // Chrome debugger
)
);

Data not appearing in component when hooking up action creators, reducers with redux-thunk

I'm having problems putting all the pieces together so as to be able to display the data on my component. I can see the data display on the chrome console, and I don't get any errors on the page, but the data does not appear on my component.
If someone could help me see what I'm doing wrong and/or what I could do better
Below is a snippet with the code.
actionCreator
// #flow
// [TODO]: Add flow
import axios from 'axios';
const ROOT_URL = `https://toilets.freska.io/toilets`;
// const Actions = /* [TODO]: add flow */
export const FETCH_TOILETS = 'FETCH_TOILETS';
export const FETCH_TOILETS_PENDING = 'FETCH_TOILETS_PENDING';
export const FETCH_TOILETS_ERROR = 'FETCH_TOILETS_ERROR';
export function fetchToilets() {
const url = `${ROOT_URL}`;
const request = axios.get(url);
return dispatch => {
console.log(`IN ACTION fetchToilets`);
dispatch({ type: FETCH_TOILETS_PENDING })
axios.get(url)
.then(
response => dispatch({
type: FETCH_TOILETS,
payload: response
}),
error => dispatch({ type: FETCH_TOILETS_ERROR, payload: error })
);
};
};
reducer_cardList & rootReducer
// #flow
// [TODO]: Add flow
import { FETCH_TOILETS } from '../actions';
// type State = {} /* [TODO]: add #flow */
const initialState = [];
const CardListReducer = (state: State = initialState, action:Action ): State => {
switch(action.type) {
case FETCH_TOILETS:
return [ ...state, action.payload.data ];
default:
state;
}
return state;
}
export default CardListReducer;
// rootReducer
// #flow
// [TODO]: Add flow
import { combineReducers } from 'redux';
import CardListReducer from './reducer_cardList';
const rootReducer = combineReducers({
toilets: CardListReducer
});
export default rootReducer;
index.js
// #flow
// [TODO]: add #flow
import * as React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import App from './App';
import rootReducer from './reducers';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
const rootElement = document.getElementById('root');
const configueStore = createStore(
rootReducer,
applyMiddleware(thunk)
);
ReactDOM.render(
<Provider store={configueStore}>
<App />
</Provider>
,
rootElement
);
registerServiceWorker();
CardList.js
/* #flow */
// [TODO]: add flow
import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchToilets } from '../../actions';
import CardItem from '../../components/CardItem/CardItem';
import './CardList.css';
type CardListProps = {
cards?: React.Node<any>
}
class CardList extends React.Component<CardListProps,{}> {
renderToilet() {
const toilets = this.props.toilets;
//const toilet = toilets.map(e => e.id)
console.log(`These are all the toilets: ${JSON.stringify(toilets)}`); // [[{"id":1,"map_id":"TOILET1","queue_time":1800,"queue_level":1,"type":"male","location":""}, ...etc
//console.log(`This is the toilet info: ${JSON.stringify(toilet)}`);
const id = toilets.map(toilet => toilet.id);
const mapId = toilets.map(toilet => toilet.map_id);
console.log(`This is the id: ${JSON.stringify(id)} and the mapId: ${JSON.stringify(mapId)}`); // This is the id: [null] and the mapId: [null]
// const queueTime = data.map(toilet => toilet.queue_time);
// const queueLevel = data.map(toilet => toilet.queue_level);
// const type = data.map(toilet => toilet.type);
// const location = data.map(toilet => toilet.location);
return (
<li key={id}>
<p>{mapId}</p>
{/*<p>{queueTime}</p>
<p>{queueLevel}</p>
<p>{type}</p>
<p>{location}</p> */}
</li>
)
}
componentDidMount() {
console.log(`fetchToilets() actionCreator: ${this.props.fetchToilets()}`);
this.props.fetchToilets();
}
render() {
return(
<section>
<ul className='card-list'>
{/* { this.props.toilet.map(this.renderToilet) } */}
{ this.renderToilet() }
</ul>
</section>
)
}
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ fetchToilets }, dispatch);
}
const mapStateToProps = ({ toilets }) => {
return { toilets }
};
export default connect(mapStateToProps, mapDispatchToProps)(CardList);
You need to update your reducer like
const CardListReducer = (state: State = initialState, action:Action ): State => {
switch(action.type) {
case FETCH_TOILETS:
return [ ...state, ...action.payload.data ];
default:
state;
}
return state;
}
your old line
return [ ...state, action.payload.data ]
replace with
return [ ...state, ...action.payload.data ];
if you want to load on every time then you can just simple
return action.payload.data;
and Your render function
renderToilet() {
const toilets = this.props.toilets;
return arr.map((item, id) =><li key={id}>
<p>{item.id}</p>
{/*<p>{queueTime}</p>
<p>{queueLevel}</p>
<p>{type}</p>
<p>{location}</p> */}
</li>)
}

Categories