Passing dynamic data to created layout. #458
-
Hi :) Would it be possible to pass dynamic data to the final created layout? In my scenario I'm creating a report builder whereby a super user can design his/her own report relating to a sub user activities. This report will be dynamic and the only values I need to pass it would be the sub users ID as well as a date for the data to be generated for that will be displayed on the report. I understand to display the form I just wrap the outputed json to the Editor with edit disabled however I can seem to see how I could pass the two arguments all my components require to display the data. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
One possible way I can think of is creating a hidden node with a properties that can hold the two values I want, that way when I render the report in non edit way and desterilize the json I know the keys that I can then inject the data, then render the editor. I will try this and update the thread with the results |
Beta Was this translation helpful? Give feedback.
-
I would suggest putting the data into a Context. And in your component you do: const data = useData();
// data is either null or the data you need
// data is always null in editor mode (<Editor enabled />)
// data can be null in (<Editor enabled={false} />) or the data you need Pseudo code for useData and the Provider import * as React from 'react';
import { useEditor } from '@craftjs/core';
// or react-query, your own fetch, etc.
import useSWR from 'swr';
const DataContext = React.createContext(null);
// pseudo code
export const useData = () => {
const { enabled } = useEditor((state) => ({ enabled: state.options.enabled }));
const data = React.useContext(DataContext);
if (!enabled) {
return null;
} else {
return data;
}
};
// retrieve userId from somewhere
export const DataContextProvider = ({ children, userId }) => {
const { enabled } = useEditor((state) => ({ enabled: state.options.enabled }));
// provide buildURL
const url = userId ? buildUrl(userId) : undefined;
const { data } = useSWR(url);
if (enabled) {
return <DataContext.Provider value={null}>{children}</DataContext.Provider>;
} else {
// while loading we render nothing, alternatively you can render a loading animation
// or add an loading flag to your context to be able to render the components which render themselves in in a loading state
if (data == null) {
return null;
} else {
return <DataContext.Provider value={data}>{children}</DataContext.Provider>;
}
}
}; |
Beta Was this translation helpful? Give feedback.
I would suggest putting the data into a Context.
And in your component you do:
Pseudo code for useData and the Provider