I have a list of settings that are used as data to instantiate web components at runtime. Each time a settings object is added to the list using a button in the main < App /> the item is looked up and is rendered at runtime. That components are stored using use useContext.
// ComponentContext initial state
const initialState = { components: [] } // components example state ['a', 'b', 'c']
// component source
export function getComponent(id) {
const ComponentA = () => {
const [info] = useState([1,2,3]);
return (<div>A</div>)
}
const ComponentA = () => {
const [info] = useState([3,4,5]);
return (<div>A</div>)
}
const componentMap = {
a: ComponentA,
b: ComponentB
}
}
// App component
function App() {
const { add, components } = useContext(ComponentContext);
return <div className="flex">
<button onClick={add('a')}>add a</button>
<button onClick={add('b')}>add b</button>
<button onClick={add('c')}>add c</button>
{components.map(id => {
const Component = componentMap[id];
return <Component key={id}/>
})}
</div>
Later on in the program I want to print out the component instance and the info array items. The info array items are unchanged after creation per component. The problem is that the components list saved in the component context doesn't contain information about the info array(might look like this ['a',b','a','c'... and so on] so I can't walk the hierarchy using the component list. Also, the info arrays are randomly generated at runtime and don't relate to the components themselves.
It looks like I should change my initialState to something like the following:
// ComponentContext initial state
// example state [{ id: 'a', info: [...] }, { id : 'c', info: [...] }]
const initialState = { components: [] }
Since add components method doesn't have access to the info arrays how can I set the info list at time of storing the newly added components?