Somehow I would like to create a shared service, creating manually the provider and accessing the context works, but using serviceprovider in order to do the same and be more flexible when using multiple services doesn't seem to provide access to the inner context.
Here is my code:
app.js
import React from 'react';
import TodosContainer from './TodosContainer';
import { TodoService } from './services/TodoService';
import { createServiceContext } from './ServiceProvider';
function App() {
const { TodoServiceProvider } = createServiceContext('TodoService');
return (
<>
<TodoServiceProvider service={TodoService}>
<TodosContainer />
</TodoServiceProvider>
</>
);
}
export default App;`
here is the serviceprovider.js
import React from 'react';
export function createServiceContext(name) {
const ServiceContext = React.createContext();
function ServiceProvider({ service, children }) {
return (
<ServiceContext.Provider value={service}>
{children}
</ServiceContext.Provider>
);
}
return {
[`${name}Context`]: ServiceContext,
[`${name}Provider`]: ServiceProvider,
};
}
and here is the TodosContainer.js:
import { createServiceContext } from './ServiceProvider';
import { useContext } from 'react';
export default function TodosContainer() {
const { TodoServiceContext } = createServiceContext('TodoService');
const TodoSvc = useContext(TodoServiceContext);
result: TodoSvc is undefined ?
I've been debugging the problem since several hours, have no idea what might be wrong.
CodePudding user response:
You are creating a new context every time instead of using the same one. You would have to cache them
import React from "react";
const cache = {};
export function createServiceContext(name) {
if (name in cache) {
return cache[name];
}
const ServiceContext = React.createContext();
function ServiceProvider({ service, children }) {
return (
<ServiceContext.Provider value={service}>
{children}
</ServiceContext.Provider>
);
}
const result = {
[`${name}Context`]: ServiceContext,
[`${name}Provider`]: ServiceProvider,
};
cache[name] = result;
return result;
}