How to create a new section on the payload on the collection and show the content on the api using API

  1. First Create a new folder inside the collection folder and create an “index.tsx” file inside that folder section
  2. In that folder, you can define the various sections, like whom you want to give access to fields, like shown below
import type { GlobalConfig } from 'payload/types';


import { checkRole } from '../collections/Users/checkRole'


export const ThemeContent: GlobalConfig = {
  slug: 'ThemeContent',
  typescript: {
    interface: 'ThemeContent',
  },
  graphQL: {
    name: 'ThemeContent',
  },
  access: {
    read: ({ data, req: { user } }) => {
      return Boolean(
        data?.status === 'published' ||
          checkRole(['admin'], user) ||
          (typeof data?.user === 'string' ? data?.user : data?.user?.id) === user?.id,
      )
    },
  },
  fields: [
    {
      name: 'loginIcon',
      type: 'upload',
      label: 'Login background',
      relationTo: 'media',
    },
      {
        name: 'loginImage',
        type: 'upload',
        label: 'Login Image',
        relationTo: 'media',
      },
    {
      name: 'title',
      type: 'text',
      // required: true,
    },
  ],
}

3. Then save the folder, after login to the website as an admin, fill out the form and save it

4. We can fetch the data, by calling the API using the fetch method as shown below

 useEffect(() => {
    const fetchUser = async () => {
      try {
        const response = await fetch('http://localhost:3000/api/users'); // Adjust the endpoint as needed
        if (!response.ok) {
          throw new Error('Failed to fetch user data');
        }
        const data = await response.json();
        setUser(data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };
    fetchUser();
  }, []);
 

Leave a comment

Your email address will not be published. Required fields are marked *