It is possible make ssr app with nested mobx stores? Problem is how serialize root store and restore it?
Example of my stores:
export default class RootStore {
session = new SessionStore(this);
ui = new UIStore();
}
export default class SessionStore {
serverActionChecking = new ActionStore(this);
}
If you are referring to the process of rendering content on the server, and then hydrating the same stores in the frontend (like Next.js), you could do something like this:
You could have a special function that creates your root store and depending on if the function is called with or without data, it calls the root store hydration method. Then the root store, after instantiation of the child stores, calls their hydration methods. Hydration data should be an object that has keys that correspond to the child stores, so you could just pass specific keys to specific stores.
function initializeStore(initialData ) {
const store = new RootStore();
if (initialData) {
store.hydrate(initialData);
}
return store;
}
class RootStore {
hydrate(data) {
if(data.childStoreOne){
this.childStoreOne.hydrate(data.childStoreOne);
}
}
}
class ChildStoreOne{
hydrate(data){
//do something with the data
}
}
Now all that is left to do is to get the hydration data to the browser. One of the solutions is to embed the data in the script tag and pass it to the initialization function.
Related
I want to build a templating engine for user profiles. After picking a design, which might consist of HTML, CSS, and JS, I would like to be able to server-side/static render a users profile page using their chosen template.
I'm looking for a good place to start / for someone to point me in the right direction. Assuming there are templates already stored in a database, or saved as files to AWS, how might I dynamically load and render the template along with the users profile data using Next.js? What might be an optimal way of storing the templates?
Thank you,
Try use nextjs GetStaticProps or GetStaticPatch
https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props
https://nextjs.org/docs/basic-features/data-fetching/get-static-props
write this function in some NextPage file
export async function getStaticProps(context) {
//all logic done here will be rendered server-side.
return {
props: {}, // will be passed to the page component as props
}
}
It can consume a database within this layer, do not want to use an external API, in some projects I use the ORM Prisma to facilitate the process.
https://www.prisma.io/nextjs
// Fetch all posts (in /pages/index.tsx)
export async function getStaticProps() {
const prisma = new PrismaClient()
const posts = await prisma.post.findMany()
return {
props : { posts }
}
}
I am beginner in writing program using Inertiajs, i have been working using both laravel and react js both separately. but in case of Inertia using to combine the two i got stuck in getting a single data from the controller and also to send bunch to the controller from the view
it's hard to understand what's your problem exactly. but as I understand your problem is transferring data between server-side and client-side nodes of your app.
to transfer data from controller to client-side(react component) :
use Inertia\Inertia;
class UsersController extends Controller
{
public function show(User $user)
{
return Inertia::render('Users/Show', [
'user' =>$user,
]);
}
}
and you can get data(user object) in your component's props.
//...
export function Show = ({user})=>{
// access to the user object
}
//...
to transfer data from client-side to server-side use :
import { Inertia } from '#inertiajs/inertia'
Inertia.get(url, data, options)
Inertia.post(url, data, options)
Inertia.put(url, data, options)
Inertia.patch(url, data, options)
Inertia.delete(url, options)
Inertia.reload(options)
for more information see Manual visits
I have this example react.js code:
const cache = new Map();
const retrieveData = (fileName, data) = {
const data = cache.get(fileName);
if (data === undefined) {
data = someDataRetrievingFunction();
cache.set(fileName, data);
return data;
}
return data;
}
function Ref({fileName}) {
return <div>{retrieveData(fileName)}</div>;
}
This code executes everytime a post is clicked and a different fileName is given. If a user were to click a post, exit, then click the same post, would the mapping cache the data that was fetched the first time? Thanks in advance!
If consider this code as is, so const cache = new Map(); is in the root of the file, i.e.
// posts.js
import React from 'react'
const cache = new Map();
// Other code
cache is singleton and it will not be reset during whole app live. And answer to your question is yes, mapping will cache the data.
But such code is not a good practice. Consider if posts.js will be used in several places of the app. In this case cache will contain previously cached data and this may create problems. For example user may expect cache to be updated, but it will never be updated until browser will be refreshed.
Another drawback is that Ref will not be rerendered on cache update. So page may looks buggy.
Another approach is to put cache inside Ref component, like below
function Ref({fileName}) {
const [cache, setCache] = React.useState({});
React.useEffect(() = {
let data = cache[fileName];
if (data === undefined) {
data = someDataRetrievingFunction();
setCache(prevCache => {
...prevCache,
[fileName]: data
});
}
}, [fileName])
return <div>{cache[fileName]}</div>;
}
In this way, cache will be stable when component is mounted. When component Ref is unmounted, cache will be flushed and on the next mount cache will be recreated.
Another option may be to put cache in redux if it can be used in several places of the app.
No, the code in the render function is run every time the component is rendered (so also at every state change). You should probably use a dedicated library like React Query which will handle the caching for you.
might be question is duplicated ,even though my business case is little bit different since I need help from experts.
First time, I am using Micro frontend architecture in current project with help of single spa framework
with reactjs.
I have experience in reactjs with redux(thunk,saga) but in single spa, I am unable to intercept the provider with store in individual MFE root component.
anybody has used reactjs with Single SPA framework along with redux with individual MFE.
my all MFE are in reactjs only.
#reactjs #redux #redux-saga.
I have implemented in some time back, was using redux for inter app communication between MFEs as well.
Store was build separately in child app.
This store would be imported by the master app and registered in global event distributor in the master app.
class GlobalEventDistributor {
constructor() {
this.stores = [];
}
registerStore(store) {
this.stores.push(store);
}
dispatch(event) {
this.stores.forEach((s) => s.dispatch(event));
}
}
This GlobalEventDistributor along with the store will be passed as a custom prop while registering application.
let storeModule = {},
customProps = {
globalEventDistributor: globalEventDistributor,
...additionalProps,
};
try {
storeModule = storeURL
? await SystemJS.import(storeURL)
: { storeInstance: null };
} catch (e) {
console.error(`Could not load store of app ${name}.`, e);
}
if (storeModule.storeInstance && globalEventDistributor) {
// add a reference of the store to the customProps
customProps.store = storeModule.storeInstance;
// register the store with the globalEventDistributor
globalEventDistributor.registerStore(storeModule.storeInstance);
}
// register the app with singleSPA and pass a reference to the store of the app as well as a reference to the globalEventDistributor
singleSpa.registerApplication(
name,
() => SystemJS.import(appURL),
hashPrefix(hash, wild),
customProps
);
After passing as customer props store and GlobalEventDispatcher will be available in the rootComponent passed to singleSpaReact of child app. From rootComponent it will be passed as a prop to Provider
I have referred below repo while implementing it.
https://github.com/me-12/single-spa-portal-example
Note: Currently we have are migrating to Module Federation instead of using singleSPA you can try that too.
I am learning React and want to create an application with Symfony4 as my backend and React frontend. I am stuck now when I need to pass some kind of data to the frontend from my backend. I don't really know what is the right way to do it? Following some tutorials I am doing it like this:
From the controller I send some data to the twig file:
/**
* #Route("/")
*/
public function homepage()
{
$date = new DateTime();
$curr_date = $date->format('Y-m-d H:i:s');
return $this->render('base.html.twig', [
'gameDate' => $curr_date
]);
}
In the twig file, I set it as a data-attribute
base.html.twig:
<div id="root" data-event-date="{{ gameDate }}">
Then I can get the variable as a dataset in my JavaScript
App.js:
const root = document.getElementById('root');
ReactDOM.render(<Homepage {...(root.dataset)}/>, root);
And render it from props.
Homepage.js:
class Homepage extends Component {
constructor(props) {
super(props)
this.state = {
prizePool: '',
gameDate: '',
numberOfPlayers: ''
}
}
onParticipateClick = (event) => {
this.setState({prizePool: Math.random()})
}
render()
{
return (
<div className="mt-c-10">
<GameInfoBox gameDate={this.props.eventDate}/>
</div>
)
}
}
This actually works, but I am concerned with showing all the information in data variables because anyone can see it. What if I want to pass user ID or something secret? There should be another way to do it right?
It depend on what you attemps, if you are working on big project, you can use API to serve backend data. Take a look here: https://www.modernjsforphpdevs.com/react-symfony-4-starter-repo/. There is a simple example.
But if you want something more use api-platform or FOSRestBundle.
"Best and safest" is a little ambiguous - do you need strict security, or safe as in code stability etc?
Instead of passing your data from controller to view (twig) and then into HTML elements or global, another way is this:
Controller loads the view file with your nav and other stuff
Controller loads React (however you do this, Webpack etc)
React calls another controller (i.e. fetch()). This controller is probably somewhere like src/Api/Controller/ as it wont render a view so keep it separate to the other controllers which do render a view
The API controller calls your DB or remote API (etc) and gets the data and sends it back as JsonResponse back to React.
React can then show the data, or an error message depending on the response status
The API controller in your MW can also handle errors and do some logging, so React just gets a 200 and the data or a 400 (or whatever) and it can show a nice message to the user as normal.