0

Is possible to run the server side props within a component in NextJS? As I understand, getServerSideProps fetches the data when entering into my page, but, is possible for it to run when rendering a component?

This is because I have the following:

export default function FichaTecnica(props) {
  const indicador = props.data;

  const crumbs = [{
    text: 'Chihuahua en Datos',
    href: '/chihuahua-en-datos'
  }, {
    text: indicador.modulo.temaIndicador,
    href: `/chihuahua-en-datos/temas/${indicador.modulo.id}/indicadores`
  }, {
    text: indicador.nombre
  }];

  return (
    <>
      <Container sx={{ mb: 3, mt: 3 }}>
        <PageBreadcrumb crumbs={[...crumbs]} />
        <TopData info={indicador} />
        <DataSheet datasheet={indicador} />
        <GraphBox history={indicador} />
        <MapButton mapa={indicador.mapa} />
        <IndicadorOwner authorID={indicador.createdBy} indicadorDate={indicador.updatedAt} />
      </Container>
    </>
  );
}

export async function getServerSideProps(context) {
  const idIndicador = context.params.idIndicador;
  const res = await fetch(
    `${process.env.INDICADORES_BASE_URL}/indicadores/${idIndicador}`
  );

  const data = await res.json();

  if (res.status === 200) {
    return {
      props: { ...data },
    };
  } else {
    return {
      props: {
        data: [],
      },
    };
  }
}

I want to fetch data on the IndicadorOwner component, and inside of it I have:

const IndicadorOwner = ({ ownerID, indicadorDate }, props) => {
    return (
        <>
            <Title variant='h4' component='h2'>Responsable</Title>
            <Grid container className={`${style.indicadorOwner}`}>

                <Grid item sm={12} md={8} lg={6} xl={6} className={`${style.cardBody}`}>
                    <Box className={`${style.cardContainer}`}>
                        <Box className={`${style.imageContainer}`}>
                            <Avatar alt='Bobby P.' src='https://media.gq.com.mx/photos/61f8318a45749103d307bf61/2:3/w_1124,h_1686,c_limit/robert%20pattinson.jpg' sx={{ width: 100, height: 100 }}>
                            </Avatar>
                        </Box>
                        <Box className={`${style.userInformation}`} >
                            <Typography variant='caption' component='h4' className={`${style.cardData}`}>
                                24 de Julio 2022
                            </Typography>
                            <Typography variant='subtitle' component='h3' className={`${style.cardData}`}>
                                Robert Pattinson
                            </Typography>
                            <Typography variant='subtitle' component='h5' className={`${style.cardData}`}>
                                Robert Douglas Thomas Pattinson (born 13 May 1986) is an English actor. Known for starring in both big-budget and independent films.
                            </Typography>
                            <br />
                        </Box>
                        <Box className={`${style.contact}`}>
                            <Link href='mailto:Bobby.P@gmail.com' className={`${style.link}`}>
                                <Avatar sx={{ width: 30, height: 30 }} className={`${style.emailIcon}`}>
                                    <MailIcon />
                                </Avatar>
                            </Link>
                        </Box>
                    </Box>
                </Grid>
            </Grid>
        </>
    )
}

export async function getServerSideProps(context) {
    const idUsuario = context.params.idUsuario;

    const res = await fetch(
        `${process.env.INDICADORES_BASE_URL}/usuarios/${idUsuario}/profile`
    );

    const data = await res.json();
    if (res.status === 200) {
        return {
            props: { ...data },
        };
    } else {
        return {
            props: {
                data: [],
            }
        }
    }
}

Now, I want to be able to use the "ownerID" into the fetching in order to retrieve my user, but, is this possible or is this the correct approach?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Miguel V
  • 606
  • 2
  • 6
  • 18
  • 2
    First of all, getServerSideProps only can be executed on the page not in the components, as it executes on the server-side, but why do you want to execute it in the component, not in the page which wraps that component? – Mina Jun 24 '22 at 18:06

1 Answers1

1

You can do two things

  1. Fetch all the data you need in getServerSideProps, potentially multiple queries and pass all the data you need into FichaTecnica to populate all components

or

  1. Fetch some "key ID's" and pass those into FichaTecnica. Then fetch additional missing data from within the component (from the frontend), e.g. using useEffect

getServerSideProps only fetches data, not return components. Use the data to hydrate components.

Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50