I am facing same problem when Cache enable I am not able to get customer session.But I find below solution
/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;
public function __construct(Template\Context $context,
\Magento\Framework\App\Request\Http $request,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Customer\Model\SessionFactory $customerSession
)
{
$this->request = $request;
$this->customerRepository = $customerRepository;
$this->_customerSession = $customerSession;
parent::__construct($context);
}
public function getCustomerId(){
$customer = $this->_customerSession->create();
var_dump($customer->getCustomer()->getId());
}
Use above code in block It is working even cache is enable.
Second Solution:
Add cacheable="false" in your xml
<referenceContainer name="content">
<block class="Vendor\Modulename\Block\Customer" name="customer.session.data" template="Vendor_Modulename::customertab.phtml" cacheable="false" />
</referenceContainer>
Add below code in block:
/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;
/**
* Construct
*
* @param \Magento\Framework\View\Element\Template\Context $context
*/
public function __construct(Template\Context $context,
\Magento\Framework\App\Request\Http $request,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Customer\Model\Session $customerSession
)
{
$this->request = $request;
$this->customerRepository = $customerRepository;
$this->_customerSession = $customerSession;
parent::__construct($context);
}
public function getOrderData(){
$customerId = $this->_customerSession->getCustomerId();
return $customerId;
}