Top

Next.Js Documentation

E-Commerce offers stunning and one-of-a-kind website demos tailored to your grocery, bakery, and online store needs. With E-Commerce, you'll find everything you require to craft the ideal website for your business. E-Commerce - your all-in-one solution!

Work With Use Context

Context API is a state management library for Next.js applications that offers a simple and efficient way to share state between components. It uses a global context object to store state, which can be accessed and updated from anywhere in the application using the useContext hook.


How to use useContext?

useContext

For Example:

index.jsx

import { createContext } from 'react';      
const AccountContext = createContext();
export default AccountContext;

AccountProvider.jsx

import React, { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import AccountContext from '.';
import request from '../../Utils/AxiosUtils';
import { useCookies } from 'react-cookie';
import { SelfAPI } from '@/Utils/AxiosUtils/API';

const AccountProvider = (props) => {
  const [cookies] = useCookies(['uat']);
  const [mobileSideBar, setMobileSideBar] = useState(false)
  const { data, refetch, isLoading } = useQuery([SelfAPI], () => request({ url: SelfAPI }), {
    enabled: false,
    select: (res) => {
      return res?.data;
    },
  });
  const [accountData, setAccountData] = useState();

  useEffect(() => {
    cookies.uat && refetch();
  }, [cookies.uat]);

  useEffect(() => {
    if (data) {
      setAccountData(data);
    }
  }, [isLoading, data]);

  return {props.children};
};

export default AccountProvider;
                    

MainLayout.jsx

The account provider is wrapped in the main layout component so that it is available to other components.

"use client";
import AccountProvider from "@/Helper/AccountContext/AccountProvider";
import SubLayout from "./SubLayout";

const MainLayout = ({ children }) => {
  return (
    <AccountProvider>
      <SubLayout children={children} />
    </AccountProvider>
  );
};

export default MainLayout;

AddressHeader.jsx

This is a file example of how to utilise the useContext in the fastkart theme.

import AccountContext from "@/Helper/AccountContext";
import { useContext, useEffect, useState } from "react";
import AddressData from "./AddressData";

const AddressHeader = () => {
  const [addressState, setAddressState] = useState([]);
  const { accountData, refetch } = useContext(AccountContext);
  useEffect(() => {
    accountData?.address.length > 0 &&
      setAddressState((prev) => [...accountData?.address]);
  }, [accountData]);

  return (
    <>
    <AddressData>
          addressState={addressState}
          setAddressState={setAddressState}
        />
    
  );
};

export default AddressHeader;