Here is the link for codesandbox
Hi Friends, I am learning about observable design pattern. I am trying to display bitcoin price updating but I am currently getting price
as undefined
. I have API being called and also created observable methods to subscribe
and notify
. I have an observer being created as constructor from the observable and trying to update the price state from API. But the price is showing as undefined. Can you please help me where am I going wrong ? Thank you
export function Observable() {
this.observers = []; //array of observer functions
}
Observable.prototype = {
subscribe: function (fn) {
this.observers.push(fn);
},
fire: function () {
this.observers.forEach((fn) => {
fn.call();
});
}
};
import React from "react";
import { getBitcoinPrice } from "./api";
import { Observable } from "./observable";
const CryptoPrice = () => {
const [price, setPrice] = React.useState(0);
React.useEffect(() => {
const bitcoinObservable = new Observable();
console.log({ bitcoinObservable });
let livePrice = bitcoinObservable.subscribe(getBitcoinPrice);
setPrice(livePrice);
console.log({ livePrice });
let newPrice = bitcoinObservable.fire();
console.log({ newPrice });
}, [price]);
return (
<>
<h3>{price ? price : "undefined"}</h3>
</>
);
};
export default CryptoPrice;
Aucun commentaire:
Enregistrer un commentaire