React-Redux re-render on dispatch inside HOC not working - react-redux

I am busy with a little proof of concept where basically the requirement is to have the home page be a login screen when a user has not logged in yet, after which a component with the relevant content is shown instead when the state changes upon successful authentication.
I have to state upfront that I am very new to react and redux and am busy working through a tutorial to get my skills up. However, this tutorial is a bit basic in the sense that it doesn't deal with connecting with a server to get stuff done on it.
My first problem was to get props to be available in the context of the last then of a fetch as I was getting an error that this.props.dispatch was undefined. I used the old javascript trick around that and if I put a console.log in the final then, I can see it is no longer undefined and actually a function as expected.
The problem for me now is that nothing happens when dispatch is called. However, if I manually refresh the page it will display the AuthenticatedPartialPage component as expected because the localstorage got populated.
My understanding is that on dispatch being called, the conditional statement will be reavaluated and AuthenticatedPartialPage should display.
It feels like something is missing, that the dispatch isn't communicating the change back to the parent component and thus nothing happens. Is this correct, and if so, how would I go about wiring up that piece of code?
The HomePage HOC:
import React from 'react';
import { createStore, combineReducers } from 'redux';
import { connect } from 'react-redux';
import AuthenticatedPartialPage from './partials/home-page/authenticated';
import AnonymousPartialPage from './partials/home-page/anonymous';
import { loggedIntoApi, logOutOfApi } from '../actions/authentication';
import authReducer from '../reducers/authentication'
// unconnected stateless react component
const HomePage = (props) => (
<div>
{ !props.auth
? <AnonymousPartialPage />
: <AuthenticatedPartialPage /> }
</div>
);
const mapStateToProps = (state) => {
const store = createStore(
combineReducers({
auth: authReducer
})
);
// When the user logs in, in the Anonymous component, the local storage is set with the response
// of the API when the log in attempt was successful.
const storageAuth = JSON.parse(localStorage.getItem('auth'));
if(storageAuth !== null) {
// Clear auth state in case local storage has been cleaned and thus the user should not be logged in.
store.dispatch(logOutOfApi());
// Make sure the auth info in local storage is contained in the state.auth object.
store.dispatch(loggedIntoApi(...storageAuth))
}
return {
auth: state.auth && state.auth.jwt && storageAuth === null
? state.auth
: storageAuth
};
}
export default connect(mapStateToProps)(HomePage);
with the Anonymous LOC being:
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { loggedIntoApi } from '../../../actions/authentication';
export class AnonymousPartialPage extends React.Component {
constructor(props) {
super(props);
}
onSubmit = (e) => {
e.preventDefault();
const loginData = { ... };
// This is where I thought the problem initially occurred as I
// would get an error that `this.props` was undefined in the final
// then` of the `fetch`. After doing this, however, the error went
// away and I can see that `props.dispatch is no longer undefined
// when using it. Now though, nothing happens.
const props = this.props;
fetch('https://.../api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(loginData)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
if(data && data.jwt) {
props.dispatch(loggedIntoApi(data));
localStorage.setItem('auth', JSON.stringify(data));
}
// else show an error on screen
});
};
render() {
return (
<div>
... onSubmit gets called successfully somewhere in here ...
</div>
);
}
}
export default connect()(AnonymousPartialPage);
the action:
// LOGGED_INTO_API
export const loggedIntoApi = (auth_token) => ({
type: 'LOGGED_INTO_API',
auth: auth_token
});
// LOGGED_OUT_OF_API
export const logOutOfApi = (j) => ({
type: 'LOG_OUT_OF_API'
});
and finally the reducer:
const authDefaultState = { };
export default (state = authDefaultState, action) => {
switch (action.type) {
case 'LOGGED_INTO_API':
// SOLUTION : changed this line "return action.auth;" to this:
return { ...action.auth, time_stamp: new Date().getTime() }
case 'LOG_OUT_OF_API':
return { auth: authDefaultState };
default:
return state;
}
};

My suggestion would be to make sure that the state that you are changing inside Redux is changing according to javascript's equality operator!. There is a really good answer to another question posted that captures this idea here. Basically, you can't mutate an old object and send it back to Redux and hope it will re-render because the equality check with old object will return TRUE and thus Redux thinks that nothing changed! I had to solve this issue by creating an entirely new object with the updated values and sending it through dispatch().
Essentially:
x = {
foo:bar
}
x.foo = "baz"
dispatch(thereWasAChange(x)) // doesn't update because the x_old === x returns TRUE!
Instead I created a new object:
x = {
foo:"bar"
}
y = JSON.parse(JSON.stringify(x)) // creates an entirely new object
dispatch(thereWasAChange(y)) // now it should update x correctly and trigger a rerender
// BE CAREFUL OF THE FOLLOWING!
y = x
dispatch(thereWasAChange(y)) // This WON'T work!!, both y and x reference the SAME OBJECT! and therefore will not trigger a rerender
Hope this helps!

Related

use loader before matching any route for context global store?

In a regular React App I'd use Redux to manage the state, where I'd dispatch the initial data before matching any route in App, however, Redux is not advised in Remix, so I'm using useContext instead.
Is there a way to call loaders to fetch initial data (e.g. session, objects, etc.) before/without having to match any route and to then store that data in the context global store and then can be accessed by any component whithin the store? That way, the API will only be called during app initialization.
I'm at this moment calling the initial data in the loader of root.tsx, getting it with useLoaderData and then passing it as a prop to StoreProvider to dispatch it in the global state, however, I don't think this should be done like that way.
export let loader: LoaderFunction = async ({ request }) => {
let user = await getUser(request);
const products = await db.product.findMany();
return { user: user?.username, products };
};
function App() {
const data = useLoaderData<LoaderData>();
return (
<html lang="en">
...
<StoreProvider initData={data}>
<body>
...
<Outlet />
<ScrollRestoration />
<Scripts />
{process.env.NODE_ENV === "development" && <LiveReload />}
</body>
</StoreProvider>
</html>
);
}
export default App;
I think doing the data loading on the root route loader is the best way.
If you don't like that approach you could also fetch on entry.server and entry.client.
For example in entry.client you probably have something like this:
import { hydrate } from "react-dom";
import { RemixBrowser } from "remix";
hydrate(<RemixBrowser />, document);
So you can change it to do the fetch before calling hydrate.
import { hydrate } from "react-dom";
import { RemixBrowser } from "remix";
fetch(YOUR_API_ENDPOINT)
.then(response => response.json())
.then(data => {
hydrate(
<YourContextProvider value={data}>
<RemixBrowser />
</YourContextProvider>,
document
)
});
And in entry.server you can change the handleRequest function to something like this:
import { renderToString } from "react-dom/server";
import { RemixServer } from "remix";
import type { EntryContext } from "remix";
export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
let response = await fetch(YOUR_API_ENDPOINT)
let data = await response.json()
let markup = renderToString(
<YourContextProvider value={data}>
<RemixServer context={remixContext} url={request.url} />
</YourContextProvider>
);
responseHeaders.set("Content-Type", "text/html");
return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders
});
}
By doing it on entry.client and entry.server the fetch will only happen once and it will never be triggered again.
I still recommend you to do it inside the loader of the root so after an action it can be fetched again to keep the data updated.

Apollo Client reactive variable state is not kept in cache after refreshing the page

I have Apollo Client running on my React app, and trying to keep authentication info in a Reactive Variable using useReactiveVar. Everything works in the dummy function when I first set the variable, however it resets the state after refreshing the app.
Here's my cache.js:
import { InMemoryCache, makeVar } from "#apollo/client";
export const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
isLoggedIn: {
read() {
return isLoggedInVar();
},
},
},
},
},
});
export const isLoggedInVar = makeVar();
export default cache;
Here's the component that reads the variable and renders different elements based on its state:
import React from "react";
import { useReactiveVar, useMutation } from "#apollo/client";
import MainButton from "../common/MainButton";
import { isLoggedInVar, userAddressVar } from "../../cache";
import { CREATE_OR_GET_USER } from "../../mutations/User";
const Profile = () => {
const isLoggedIn = useReactiveVar(isLoggedInVar);
const [createOrGetUser] = useMutation(CREATE_OR_GET_USER);
const handleCreateOrGetUser = () => {
const loginInput = {
address: 'text',
};
createOrGetUser({
variables: {
loginInput: loginInput,
},
}).then((res) => {
isLoggedInVar(true);
});
};
const profileComponent = isLoggedIn ? (
<div>Logged In</div>
) : (
<div onClick={handleCreateOrGetUser} className="profile-image"></div>
);
return (
<div className="profile-container">
{profileComponent}
</div>
);
};
export default Profile;
This component gets re-rendered properly when I invoke handleCreateOrGetUser, however, when I refresh the page, it resets the isLoggedInVar variable.
What would be the proper way to use Reactive Variables here to persist the cache?
It's not currently achievable using Apollo API according to their documentation.
There is currently no built-in API for persisting reactive variables,
but you can write variable values to localStorage (or another store)
whenever they're modified, and initialize those variables with their
stored value (if any) on app load.
There is a PR for that. https://github.com/apollographql/apollo-client/pull/7148

React-Redux-Saga TypeError: Cannot read property 'data' of null

Please lemme know I'm stuck past 3 days.I'm newbie to Redux Saga I'm not understanding where I'm going wrong. As I've just started dont have much experience, not understood the sagas that well:( .But I wanna get onto it.
I need to show sales data in line graph following is my code
Sample Json Data
{"data":[{"year":"2014","Sales":4390,"Orders":3800},{"year":"2013","Sales":4490,"Orders":4300},{"year":"2015","Sales":2200,"Orders":3400},{"year":"2016","Sales":1280,"Orders":2398},{"year":"2017","Sales":5000,"Orders":4300},{"year":"2018","Sales":4780,"Orders":2908},{"year":"2019","Sales":5890,"Orders":4800}]}
Admin Folder
adminActions.js
import {GET_SALES_DATA} from '../constants/actionTypes';
export const getSales =()=>({
type:GET_SALES_DATA
});
adminReducer.js
import {GET_SALES_DATA,SALES_DATA_RECEIVED} from '../constants/actionTypes';
const adminReducer=(state={},action)=>{
switch(action.type){
case GET_SALES_DATA:
return {...state};
case SALES_DATA_RECEIVED:
return {...state,payload:action.salesDataPerYear} **//issue here payload data is not received state is not getting updated with the data**
default:
return state;
}
}
export default adminReducer;
adminSaga.js
import {put,takeLatest,all} from 'redux-saga/effects';
import {GET_SALES_DATA,SALES_DATA_RECEIVED} from '../constants/actionTypes';
function *getSales(){
console.log("5saga")
const salesDataPerYear=yield fetch("api call")
.then(response=>response.data);
yield put({type:SALES_DATA_RECEIVED,salesDataPerYear:salesDataPerYear})
}
function *actionWatcher(){
yield takeLatest(GET_SALES_DATA,getSales)
}
export default function *rootSaga(){
yield all([
actionWatcher(),
]);
}
dashboard.js
const mapStateToProps=(state)=>({
data:state.salesDataPerYear
})
const mapDispatchToProps = {
getSales:getSales
};
class DashboardMain extends React.Component {
componentDidMount(){
this.props.getSales()
}
render() {
const { classes,data } = this.props;
// const { data } =this.state;
**console.log(data)// data not rendering in console is the saga i've written is correct?**
return (
<div className={classes.root}>
<Grid container spacing={24}>
<Grid item xs={12}>
<SimpleLineChart data={data} />**//commented**
</Grid>
<Grid item xs={12}>
<SimpleTable />
</Grid>
</Grid>
</div>
);
}
}
DashboardMain.propTypes = {
classes: PropTypes.object.isRequired,
};
const Dashboard=connect(mapStateToProps,mapDispatchToProps)(DashboardMain);
simleLineChart.js (UPDATED)
<LineChart data={ this.props.data }> **// TypeError: Cannot read property 'props' of undefined**
Following is store folder
index.js
import createSagaMiddleware from 'redux-saga';
import {createStore,applyMiddleware} from 'redux';
import {logger} from 'redux-logger';
import rootSaga from '../adminDashboard/adminSaga';
import reducers from '../adminDashboard/adminReducers';
const sagaMiddleware=createSagaMiddleware();
const store=createStore(
reducers,
applyMiddleware(sagaMiddleware,logger),
);
sagaMiddleware.run(rootSaga);
export default store;
Data is not shown in line chart.I know there's some error in my saga but I dont know what is it :(.
Can anyone please lemme know where I'm going wrong. Anything which I've missed onto. Any help is appreciated.
Updates
Data not rendering in console is the saga I've written is corrector I've missed onto something?
undefined
redux-logger.js:389 action GET_SALES_DATA # 12:38:06.302
redux-logger.js:400 prev state {}
redux-logger.js:404 action {type: "GET_SALES_DATA"}type: "GET_SALES_DATA"__proto__: Object
redux-logger.js:413 next state {}
adminSaga.js:7 5saga
Response {type: "cors", url: "API call", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "cors"url: "API call"__proto__: Response
redux-logger.js:389 action SALES_DATA_RECEIVED # 12:38:07.103
redux-logger.js:400 prev state {}__proto__: Object
redux-logger.js:404 action {type: "SALES_DATA_RECEIVED", payload: Response, ##redux-saga/SAGA_ACTION: true}payload: Responsebody: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "cors"url: "API call"__proto__: Responsetype: "SALES_DATA_RECEIVED"##redux-saga/SAGA_ACTION: true__proto__: Object
redux-logger.js:413 next state {payload: undefined}payload: undefined__proto__: Object
I've commented the simpleLineChart there some issue with the saga and reducer I dont get the result.I updated with the log please check. the API call is retriving the data. But in reducer I'm doing wrong which I've no idea.Please lemme know
It worked like a charm horray:) after three days ufff .I learnt much worthy.the saying goes true to me "We learn more from our mistakes" Thanks to #RussCoder
adminSaga.js
try{
const salesDataPerYear=yield fetch("https://api.myjson.com/bins/78b9w")
.then(response=>response.json())
yield put({type:SALES_DATA_RECEIVED,payload:salesDataPerYear.data})
}
adminReducer.js
case SALES_DATA_RECEIVED:
return {...state,payload:action.payload };
dashbord.js
const mapStateToProps=state=>{
return{
dataSales:state //have changes data to dataname
}
};

Redux + storybook throws warning about changing store on the fly even with module.hot implemtended

I'm using storybook and I want to add redux as decorator.
Whe running storybook, I got warning in console:
<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.
It's my code for config storybook:
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */
import React from 'react';
import { configure, storiesOf } from '#storybook/react';
import { Provider as ReduxProvider } from 'react-redux';
import forEach from 'lodash/forEach';
import unset from 'lodash/unset';
import Provider from 'components/Provider';
import initStore from 'utils/initStore';
import messages from '../lang/en.json';
const req = require.context('../components', true, /_stories\.js$/);
const ProviderDecorator = (storyFn) => {
const TheProvider = Provider(() => storyFn());
return (
<ReduxProvider store={initStore()}>
<TheProvider key={Math.random()} now={1499149917064} locale="en" messages={messages} />
</ReduxProvider>
);
}
function loadStories() {
req.keys().forEach((filename) => {
const data = req(filename);
if (data.Component !== undefined && data.name !== undefined && data.stories !== undefined) {
const Component = data.Component;
const stories = storiesOf(data.name, module);
stories.addDecorator(ProviderDecorator);
let decorator = data.stories.__decorator;
if (data.stories.__decorator !== undefined) {
stories.addDecorator((storyFn) => data.stories.__decorator(storyFn()));
}
forEach(data.stories, (el, key) => {
if (key.indexOf('__') !== 0) {
stories.add(key, () => (
<Component {...el} />
));
}
});
} else {
console.error(`Missing test data for ${filename}!`)
}
});
}
configure(loadStories, module);
and initStore file:
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducers from 'containers/redux/reducers';
export default () => {
const store = createStore(
reducers,
{},
composeWithDevTools(applyMiddleware(thunkMiddleware), autoRehydrate()),
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../containers/redux/reducers', () => {
const nextReducers = require('../containers/redux/reducers'); // eslint-disable-line global-require
store.replaceReducer(nextReducers);
});
}
persistStore(store);
return store;
};
So as you can see I followed instructions from link in warning. What have I done wrong and how can I remove this warning? I know it won't show on production server, but it's pretty annoying in dev mode. :/
The reason this is happening has to do with the way Storybook hot-loads.
When you change your story, that module is hot-loaded, meaning that the code inside it is executed again.
Since you're using a store creator function and not a store instance from another module, the actual store object that is being passed to ReduxProvider on hot-load is new every time.
However, the React tree that is re-constructed is for the most part identical, meaning that the ReduxProvider instance is re-rendered with new props instead of being re-created.
Essentially, this is changing its store on the fly.
The solve is to make sure that ReduxProvider instance is new, too, on hot-load. This is easily solved by passing it a unique key prop, e.g.:
const ProviderDecorator = (storyFn) => {
const TheProvider = Provider(() => storyFn());
return (
<ReduxProvider key={Math.random()} store={initStore()}>
<TheProvider key={Math.random()} now={1499149917064} locale="en" messages={messages} />
</ReduxProvider>
);
}
From React Keys:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

Loading component data asynchronously server side with Mobx

I'm having an issue figuring out how to have a react component have an initial state based on asynchronously fetched data.
MyComponent fetches data from an API and sets its internal data property through a Mobx action.
Client side, componentDidMount gets called and data is fetched then set and is properly rendered.
import React from 'react';
import { observer } from 'mobx-react';
import { observable, runInAction } from 'mobx';
#observer
export default class MyComponent extends React.Component {
#observable data = [];
async fetchData () {
loadData()
.then(results => {
runInAction( () => {
this.data = results;
});
});
}
componentDidMount () {
this.fetchData();
}
render () {
// Render this.data
}
}
I understand that on the server, componentDidMount is not called.
I have something like this for my server:
import React from 'react';
import { renderToString } from 'react-dom/server';
import { useStaticRendering } from 'mobx-react';
import { match, RouterContext } from 'react-router';
import { renderStatic } from 'glamor/server'
import routes from './shared/routes';
useStaticRendering(true);
app.get('*', (req, res) => {
match({ routes: routes, location: req.url }, (err, redirect, props) => {
if (err) {
console.log('Error', err);
res.status(500).send(err);
}
else if (redirect) {
res.redirect(302, redirect.pathname + redirect.search);
}
else if (props) {
const { html, css, ids } = renderStatic(() => renderToString(<RouterContext { ...props }/>));
res.render('../build/index', {
html,
css
});
}
else {
res.status(404).send('Not found');
}
})
})
I have seen many posts where an initial store is computed and passed through a Provider component. My components are rendered, but their state is not initialized. I do not want to persist this data in a store and want it to be locally scope to a component. How can it be done ?
For server side rendering you need to fetch your data first, then render. Components don't have a lifecycle during SSR, there are just render to a string once, but cannot respond to any future change.
Since your datafetch method is async, it means that it cannot ever affect the output, since the component will already have been written. So the answer is to fetch data first, then mount and render components, without using any async mechanism (promises, async etc) in between. I think separating UI and data fetch logic is a good practice for many reasons (SSR, Routing, Testing), see this blog.
Another approach is to create the component tree, but wait with serializing until all your promises have settled. That is the approach that for example mobx-server-wait uses.

Resources