use loader before matching any route for context global store? - remix.run

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.

Related

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

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

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!

Jest + Enzyme: test Redux-form

My application has a lot of redux-form. I am using Jest and Enzyme for unit testing. However, I fail to test the redux-form. My component is a login form like:
import { login } from './actions';
export class LoginForm extends React.Component<any, any> {
onSubmit(values) {
this.props.login(values, this.props.redirectUrl);
}
render() {
const { handleSubmit, status, invalid } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<TextField label="Email" name="email">
<TextField type="password" label="Password" name="password" autoComplete/>
<Button submit disabled={invalid} loading={status.loading}>
OK
</Button>
</form>
);
}
}
const mapStateToProps = (state) => ({
status: state.login.status,
});
const mapDispatchToProps = { login };
const form = reduxForm({ form: 'login' })(LoginForm);
export default connect(mapStateToProps, mapDispatchToProps)(form);
Mock the store, Import connected component
redux-form uses the store to maintain the form inputs. I then use redux-mock-store:
import ConnectedLoginForm from './LoginForm';
const configureStore = require('redux-mock-store');
const store = mockStore({});
const spy = jest.fn();
const wrapper = shallow(
<Provider store={store}>
<ConnectedLoginForm login={spy}/>
</Provider>);
wrapper.simulate('submit');
expect(spy).toBeCalledWith();
But in this way, the submit is not simulated, my test case failed:
Expected mock function to have been called with: []
But it was not called.
Mock the store, Import React component only.
I tried to create redux form from the testing code:
import { Provider } from 'react-redux';
import ConnectedLoginForm, { LoginForm } from './LoginForm';
const props = {
status: new Status(),
login: spy,
};
const ConnectedForm = reduxForm({
form: 'login',
initialValues: {
email: 'test#test.com',
password: '000000',
},
})(LoginForm);
const wrapper = shallow(
<Provider store={store}>
<ConnectedForm {...props}/>
</Provider>);
console.log(wrapper.html());
wrapper.simulate('submit');
expect(spy).toBeCalledWith({
email: 'test#test.com',
password: '000000',
});
In this case, i still got error of function not called. If I add console.log(wrapper.html()), I got error:
Invariant Violation: Could not find "store" in either the context or
props of "Connect(ConnectedField)". Either wrap the root component in
a , or explicitly pass "store" as a prop to
"Connect(ConnectedField)".
I cannot find documentations on official sites of redux-form or redux or jest/enzyme, or even Google.. Please help, thanks.
I used the real store (as redux-mock-store does not support reducers) and redux-form's reducer, it worked for me. Code example:
import { createStore, Store, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { reducer as formReducer } from 'redux-form';
const rootReducer = combineReducers({
form: formReducer,
});
let store;
describe('Redux Form', () => {
beforeEach(() => {
store = createStore(rootReducer);
});
it('should submit form with form data', () => {
const initialValues = {...};
const onSubmit = jest.fn();
const wrapper = mount(
<Provider store={store}>
<SomeForm
onSubmit={onSubmit}
initialValues={initialValues}
/>
</Provider>
);
const form = wrapper.find(`form`);
form.simulate('submit');
const expectedFormValue = {...};
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0][0]).toEqual(expectedFormValue);
});
});
You can find the answer here: https://github.com/tylercollier/redux-form-test
In short, you can use shallow dive() function to test higher-order component, but in your case, you have a higher-order component inside a higher-order component.
You need to break you component into two components, the first one is a presentation component, without
const form = reduxForm({ form: 'login' })(LoginForm);
export default connect(mapStateToProps, mapDispatchToProps)(form);
You then wrap the first component into the second component (container component).
You can easily test the first component (presentation component)
I had the similar problem. The answer can be found here https://github.com/airbnb/enzyme/issues/1002.
Long story short, you should pass store as a prop into your form and use .dive() function on the wrapper.
Regards
Pavel
I made a tool which helps with problems like that. It make a test-cases with real data (chrome extension collect it and save to file) which you can run by CLI tool.
I recommend you to try it: https://github.com/wasteCleaner/check-state-management

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