Require Help with API connections (CRA + Cockpit CMS)

Hi there,

I am exploring TinaCMS, trying to integrate inline forms with my site (CRA). On my test component, I got the editing part working by following the Tutorial. Also I am new to React :smiley:

As a backend, I am using Cockpit CMS (very similar to Strapi).

The onSubmit is whats causing me some headache. So I am loading the “pages” from the API with loadInitialValues. I store its raw form in the local component state. The relevant part is passed on to the initialValues.

        .then((res) => {
          setData(res);
          return res.entries[0].content;
        });

Then in onSubmit I am trying to combine formData with the raw page json in data state.

But within the onSubmit scope I dont have access to the data state. Any Idea how something like this could work? I would need to send back the entire data with the modified content property so the API can match it to an entry and save it.

Here is my Home component:

export default function Home() {
  const [data, setData] = useState({});
  const cms = useCMS();
  const formConfig = {
    id: './data/data.json',
    loadInitialValues() {
      return fetch('http://localhost:9000/api/collections/get/pages')
        .then((response) => response.json())
        .then((res) => {
          setData(res);
          return res.entries[0].content;
        });
    },
    onSubmit(formData) {
      console.log(formData, data);
      return fetch('http://localhost:9000/api/collections/save/pages', {
        method: 'post',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          ...data,
          entries: [...formData],
        }),
      })
        .then((res) => res.json())
        .then((entry) => console.log(entry))
        .catch((e) => {
          cms.alerts.error('Error Saving Content');
          console.error(e);
        });
    },
  };
  const [, form] = useForm(formConfig);
  usePlugin(form);
  return (
    <InlineForm form={form}>
      <InlineBlocks name="blocks" blocks={HOME_BLOCKS} />
    </InlineForm>
  );
}

Hi there @alex_h!

If I understand correctly, the problem is that when data comes from your API and goes into the form state, it is “lossy” and thus you cannot reconstruct the entire data object from the current form state when it is submitted.

This isn’t really a case we’ve accounted for in Tina. However, I think the best approach here would be to re-fetch the page data in your onSubmit handler, and then merge this “fresh” copy of the data with the modified formData values passed to the function.

@dj Thanks for your reply. This approach should work, I’ll test it.

Thanks for clarifiing!

1 Like