Search code examples
reactjsjsonschemareact-jsonschema-forms

How to correctly preselect relevant rjsf `anyOf` item on <Form> mount, based on `formData`?


I'm working with rjsf forms that save formData to the server. Users can re-open any form and it should re-populate with the previously saved formData. But, I'm having trouble getting the right oneOf/anyOf option selected when repopulating the Form on mount.

For example with the following code, I would like the second anyOf option to be pre-selected when the Form mounts:

import Form from "@rjsf/core";

function Test() {
  return <Form formData={formData} schema={schema as any} />;
}

export default Test;

const formData = {
  item: "second",
  secondProp: "abc"
};

const schema = {
  $id: "xxx",
  type: "object",

  anyOf: [
    {
      type: "object",
      title: "first",
      properties: {
        item: { type: "string", enum: ["first"], default: ["first"] },
        firstProp: { type: "string" }
      }
    },

    {
      type: "object",
      title: "second",
      properties: {
        item: { type: "string", enum: ["second"], default: ["second"] },
        secondProp: { type: "string" }
      }
    }
  ]
};

Codesandbox demo here

I have no idea why, but the above mentioned code did actually work in our project for a long time, even though I was unable to replicate this behaviour anywhere else! Unfortunately it recently broke even there and now we're boned.

So I have two questions:
  1. What could cause this pattern to work in our project, but not anywhere else?
  2. Are there any working ways to pre-select the correct item?

Solution

  • This bug was fixed in RJSF v5 🎉🎉