samedi 28 août 2021

Could there be caused any problem creating a modal component using observer pattern like this?

Okay I've never looked into design patterns and so far what I've been doing I've created a modal component that takes children and in every component that I used it I was creating a state to check if I should show modal or not like this:

const Modal = ({...someOtherProps,children})=>{
   
return(
  <div>{children}</div>
)
}

and in every single component where I needed to show modal I was doing like

const Component1 =() =>{
const [showModal,setShowModal] = useState(false);
  

return (
<div>
<button onClick={setShowModal.bind(null,true)}>Add Data</button>

{showModal && <Modal>
<AddDataForm/>
</Modal>
</div>

)

}

I knew this is not the best way of doing it and I looked up at design patterns as soon as I saw the Observer Pattern I thought that this would solve this problem, how I changed it now is like this:

I created a class that will act as the Observable

class ModalObservable {
  constructor() {
    this.open = false;
    this.child = null;
    this.subscriber = null;
  }

  setSubscriber(sub) {
    this.subscriber = sub;
  }

  subscribe(child) {
    this.child = child;
    this.open = true;
    this.notify();
  }

  unsubscribe() {
    this.child = null;
    this.open = false;
    this.notify();
  }

  notify() {
    this.subscriber(() => ({ ...this }));
  }
}


export const modalObservable = new ModalObservable();

const Modal = () => {
  const [modal, setModal] = useState(null);
  console.log(modal);
  useEffect(() => {
    modalObservable.setSubscriber(setModal);
  }, []);
  return modal?.open ? <div>{modal.child}</div> : null;
};

const Component = () => {
  return <div>This is a modal child</div>;
};

and now whenever I have to use it in a component I Just do

const MyComponent = ()=>{

return (

  <button onClick={()=>{
modalObservable.subscribe(<AddDataForm/>)
}}>Add Data</div>
)
}

I am wondering if there could be any down side to this?

Aucun commentaire:

Enregistrer un commentaire