access fetched data outside of function component in NextJs

Viewed 33

I have this code where I import a constant named colors that container the colors needed for my project :

import styled from 'styled-component';
import colors from '../utils/style/colors';

const Container = styled.div`
  background-colors:${colors.background}
`;

const BlogPage = () => {

  return (
    <Container>
      Main Contaienr
    </Container>
  );
};

export default BlogPage;

Now I wanna import the colors from a database.

I tried getStaticProps, but I could not use the props outside of the function component.

My question is how can I fetch data and use it outside the function component i.e. : inside a styled-componen

1 Answers

You can try to solve this problem with ThemeProvider styled-components.

  1. With getStaticProps we will get the data (styles) from the database.
  2. Wrap the page with a ThemeProvider and pass the data from getStaticProps to the provider.
  3. Now, we can use our styles from the database in the components.

pages/index.js

import { ThemeProvider } from 'styled-components';
import { BlogPage } from '../components/BlogPage.js';

export default function IndexPage({ theme }) {
  return (
    <ThemeProvider theme={theme}>
      <BlogPage />
    </ThemeProvider>
  );
}

export async function getStaticProps(context) {
  const databaseColors = {
    main: 'mediumseagreen',
    text: 'white',
  };

  return {
    props: {
      theme: databaseColors,
    },
  };
}

components/BlogPage.js

import styled from 'styled-components';

const Container = styled.div`
  background-color:${({ theme }) => theme.main};
  color: ${(props) => props.theme.text};
`;

export const BlogPage = () => {
  return <Container>Main Contaienr</Container>;
};

export default BlogPage;

Edit dazziling-code

Related