I have an array that via useState hook, I try to add elements to the end of this array via a function that I make available through a context. However the array never gets beyond length 2, with elements [0, n] where n is the last element that I pushed after the first.
I have simplified this a bit, and haven't tested this simple of code, it isn't much more complicated though.
MyContext.tsx
interface IElement = {
title: string;
component: FunctionComponent<any>;
props: any;
}
interface IMyContext = {
history: IElement[];
add: <T>(title: string, component: FunctionComponent<T>, props: T) => void
}
export const MyContext = React.createContext<IMyContext>({} as IMyContext)
export const MyContextProvider = (props) => {
const [elements, setElements] = useState<IElement[]>([]);
const add = <T extends any>(title: string, component: FunctionComponent<T>, props: T) => {
setElements(elements.concat({title, component, props}));
}
return (
<MyContext.Provider values={{elements, add}}>
{props.children}
</MyContext.Provider>
);
}
In other elements I use this context to add elements and show the current list of elements, but I only ever get 2, no matter how many I add.
I add via onClick from various elements and I display via a sidebar that uses the components added.
SomeElement.tsx
const SomeElement = () => {
const { add } = useContext(MyContext);
return (
<Button onClick=(() => {add('test', MyDisplay, {id: 42})})>Add</Button>
);
};
DisplayAll.tsx
const DisplayAll = () => {
const { elements } = useContext(MyContext);
return (
<>
{elements.map((element) => React.createElement(element.component, element.props))}
</>
);
};
history
? What ishistory
set to? – Jacobelements.concat([{title, component, props}])
– Ibraheem[].concat('woo') -> ['woo']
– Jacobhistory
supposed to be the same aselements
or is there some layer in between? I'm confused because you're passing<MyContext.Provider values={{history, add}}>
(also it should be justvalue
). Just want to make sure you're instantiating your provider correctly. – Jacob