Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
3
Indexable
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";


const dataContext = React.createContext()

export const DataProvider = ({ children }) => {
  const [data, setData] = React.useState(1)

  return (
    <dataContext.Provider value={[data, setData]}>
      {children}
    </dataContext.Provider>
  )
}


const App = () => {
  return (
    <DataProvider>
      <h1>Hello!</h1>
      <Consumer />
    </DataProvider>
  );
};

const useMyContext = () => {
  const [data, setData] = React.useContext(dataContext);
  return { data, setData };
};

const Consumer = () => {
  const { data } = useMyContext();

  return (
    <>
      <h3>This is the consumer</h3>
      <p>
        <strong>Data:</strong> {data}
      </p>
      <ChangeData />
    </>
  );
};

const useSendReq = () => {
  const { data } = useMyContext();
  return () => {
    if (data === 2) {
      console.log("działa", data);
    } else {
      console.log("nie działa", data);
    }
  };
};

const useMyHandler = (callback) => {
  
  const checkIfSendData = useSendReq();
  return () => {
    callback()
    checkIfSendData()
  }
}

const ChangeData = () => {
  const { setData } = useMyContext();
  const checkIfSendData = useSendReq();
  const handleChange = () => {
    setData(2);
    checkIfSendData();
  };

  const hanlder2 = useMyHandler(() => setData(2))
  return <button onClick={hanlder2}>Click to change data!</button>;
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);