How to get shop name in react pages using session ?

How to get shop name in react pages using session ?

Kamal_Berriga
Shopify Partner
16 0 0

I'm building out a nodejs with reactjs front-end for an embedded application and was wondering how would be the best way to get a shop name in react pages ?

Reply 1 (1)

EcomGraduates
Shopify Partner
632 52 90

Hello there  

To get the shop name in a React application using a session, you can follow these steps:

 

  1. First, you need to make sure that your server is configured to store session information. This typically involves setting up a session store (such as express-session) and setting the appropriate options in your server-side code.
  2. Once the server is set up to store session information, you can access the session data from your React components by using an HTTP client library (such as axios) to send a request to the server and retrieve the session data.
  3. In your React component, you can use the useEffect hook to send a request to the server to retrieve the session data when the component mounts. Here's an example of how this might look:

 

import axios from 'axios';

function MyComponent() {
  const [shopName, setShopName] = useState(null);

  useEffect(() => {
    // Send a request to the server to retrieve the session data
    axios.get('/api/session').then(response => {
      // Update the shopName state variable with the shop name from the session data
      setShopName(response.data.shopName);
    });
  }, []);

  return (
    <div>
      {/* Render the shop name if it has been retrieved from the server */}
      {shopName ? <p>Shop name: {shopName}</p> : <p>Loading shop name...</p>}
    </div>
  );
}

 

  1. On the server side, you can use the req.session object to access the session data. Here's an example of how you might retrieve the shop name from the session in a route handler:

 

app.get('/api/session', (req, res) => {
  res.json({ shopName: req.session.shopName });
});

 

 

hope this helps!


If this fixed your issue, likes and accepting as a solution are highly appreciated.

Build an online presence with our custom built Shopify Theme EcomifyTheme