I am brand new to react, so I apologize if this is a very basic question. I wasn't able to find the answer anywhere.
I have an ExtensionsContext
component that stores an array of Extension class objects as the state.
import React, { useContext, useState } from 'react'
const ExtensionsContext = React.createContext()
export function useExtensions() {
return useContext(ExtensionsContext)
}
export function ExtensionsProvider ({ children }) {
const [exts, setExtensions] = useState(startingExtensions) // startingExtentions is an array of Extention class objects
AppExtensions = {
extensions: exts,
update: function () { setExtensions(this.extensions) }
}
return (
<ExtensionsContext.Provider value={AppExtensions}>
{children}
</ExtensionsContext.Provider>
)
}
class Extension {
constructor (name, index) {
this.name = name
this.isOpen = false
this.id = index
}
open () {
this.isOpen = true
AppExtensions.update()
}
close () {
this.isOpen = false
AppExtensions.update()
}
}
These extensions are being used in a component that lists and groups them between open and closed. Currently, if I call the open method on one of the Extensions, it will change the extension value, but not re-render any components. I currently have it set up so that when the button that is clicked, it toggles a boolean state in the component between true and 1 to force a re-render, but I know I am doing something wrong and that there is a better solution. This also doesn't work if I am using these extensions in multiple places. I imagine the problem has to do with the fact that I am passing in an AppExtensions
object and a copy of exts
in rather than directly passing exts
in. I want to be able to call extension.open()
on a click and handle all of the logic inside the ExtensionsProvider
.