Commit 9c42371e authored by Balasuriya D.A.M.'s avatar Balasuriya D.A.M.

Creating Context/Use ContextHook Frontend

parent 5bb926e8
import { createContext, useContext, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
const ChatContext = createContext();
const ChatProvider = ({ children }) => {
const [user, setUser] = useState();
const history = useHistory();
useEffect(() => {
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
setUser(userInfo);
//check if user is loged in
if (!userInfo) {
history.pushState("/");
}
}, [history]);
return (
<ChatContext.Provider value={{ user, setUser }}>
{children}
</ChatContext.Provider>
);
};
export const ChatState = () => {
return useContext(ChatContext);
};
export default ChatProvider;
import React from "react";
import { useEffect } from "react";
import {
Container,
Box,
......@@ -11,8 +12,21 @@ import {
} from "@chakra-ui/react";
import Login from "../components/Authentication/Login";
import Signup from "../components/Authentication/Signup";
import { useHistory } from "react-router-dom";
const Homepage = () => {
const history = useHistory();
useEffect(() => {
const user = JSON.parse(localStorage.getItem("userInfo"));
//check if user is loged in
if (user) history.push("/chats");
}, [history]);
return (
//use container from chakra ui and remove div
<Container maxW="xl" centerContent>
......
......@@ -4,16 +4,17 @@ import "./index.css";
import App from "./App";
import { ChakraProvider } from "@chakra-ui/react";
import { BrowserRouter } from "react-router-dom";
import ChatProvider from "./Context/ChatProvider";
ReactDOM.render(
<React.StrictMode>
<ChatProvider>
<BrowserRouter>
<ChakraProvider>
<App />
</ChakraProvider>
</BrowserRouter>
</React.StrictMode>,
</ChatProvider>,
document.getElementById("root")
//rendering everything on root tag
);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment