I need to consume Context API within modules (not components).
In my app, when a user logs in, I store his data in a context (just to sync his data between components).
Storing this data in other place, and not in the state of a Context, is not the best option to synchronize the data between all the routes of my app.
I also have my "API" to connect with the server and make things like "getContent", "getMessage"... Until now, I was passing a "parse callback" (just to parse the server responses) to the "API" methods.
function ComponentA() {
const parseContent = (contentDoc) => {
// get current user data from context (the component is a consumer)
// parse the data
}
...
const content = await api.getContent(contentId, parseContent)...
...
}
function ComponentB() {
const parseMessage = (contentDoc) => {
// get current user data from context (the component is a consumer)
// parse the message data...
// if the message has "content", then parse the content (same as parseContent)
}
...
const messages = await api.getMessages(messageId, parseMessage)...
...
}
As you can see, this is something that makes me duplicating code. Because "parseContent" is can perfectly be used inside "parseMessage"
Now, I am trying to move the "parsers" methods to other modules, but some of these methods needs to consume the current user data (which is in a context). Something which makes my idea impossible to implement.
Is it common to pass "parse" callbacks to api methods in React? (Honestly, for me, this seems shitty coding) Is there any way to consume the context within a module? Any ideas?
Thank you.
Aucun commentaire:
Enregistrer un commentaire