I have a context that using a class instance as context value. After I updated the class instance. The change doesn't reflect in the consumer. Consumer still get the old class value. Can someone point me the direction of how to achieve this?
// Service class
class Service {
name = "oldName"
function changeName(newName){
this.name = newName;
}
}
//Context provider
function App() {
const service = new Service();
return (
<ServiceContext.Provider value={service}>
<Home />
</ServiceContext.Provider>
);
}
Then I try to change the name attribute of this service in one component.
import React, { useContext } from "react";
const SomeComponent = () => {
const service = useContext(ServiceContext);
const onClick = () => {
service.changeName('newName')
console.log(service.name) //here the name has updated
}
return <button onClick={onClick}>Change</h1>;
};
And try to get the updated value from the component.
//Context consumer
import React, { useContext } from "react";
const MyComponent = () => {
const service = useContext(ServiceContext);
return <h1>{service.name}</h1>;
};
but in another consumer. service.name didn't get update. May I know why is that?