Am I really supposed to specify such long paths to objects?

I’m a beginner and don’t really understand why I have to specify such long paths after receiving data from the backend api.
For example, I get a site-settings with logo image:

const siteSettings = () => {
  return axios
    .get<I_Data>(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/site-setting`, {
      params: {
        populate: '*',
      },
    })
    .then((res) => {
      console.log(res.data.data.attributes.Logo.data.attributes.url);
      return res.data;
    });
};

and get this data on nextjs page:

export const getStaticProps = async () => {
  const data = await siteSettings();

  return {
    props: {
      data,
    },
  };
};

To display the url in the Image component, I need to write like that? :

<Image src={`${process.env.NEXT_PUBLIC_BACKEND_API_URL}`/props.data.attributes.Logo.data.attributes.url}> </Image>

It’s kind of too cumbersome, isn’t it? Are there any more concise solutions?
And should I store this site-settings (Which will contain logos, phone numbers, emails, etc.) somewhere in the store?

Hey Poylar, thanks for posting your query.

The decision to structure responses as they currently are for v4 was controversial and is up for review in v5 discussions. It’s a way of separating the response’s meta values from data and allows for finely tuned responses using the populate mechanism Strapi’s entity service comes with.

To make your code more concise you could add a utility function for images, that prepends your API url and looks in data.attributes for the values you need. You can add even logic here to gracefully return a placeholder or return an error if a property cannot be located. Using lodash’s get method works well in this use case.

For further reading please see this discussion

And in response to your second question, you can if you choose to put these shared values into your React store. There is no wrong answer if the end results if the render you require.
Depending on the number of shared values putting them against the component that requires them is usually the most sensible approach as a store is really for mutable values used across multiple components. I hope that helps!

1 Like