gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Initially populate domain model with server request? #361

Closed dvwright closed 7 years ago

dvwright commented 7 years ago

Hi, this an inquiry/feature request, not an issue.

I would like to do something like this.

// in place of locally defined var Gender = t.enums({ M: 'Male', F: 'Female' });

// get data from a server request var Gender = t.remote('enums', 'http://server/request');

var Person = t.struct({ name: t.String, gender: Gender });

is there currently a way to do something like this?

Thank you

volkanunsal commented 7 years ago

https://github.com/gcanti/tcomb-json-schema

eteeselink commented 7 years ago

I don't understand how @volkanunsal's response is related, but remember that because tcomb types are entirely defined at runtime, this is possible in the usual way: just fetch the enum data with AJAX and then pass it to t.enums.

Use your favourite AJAX function to fetch enum data from your server:

fetch("http://server/request")
    .then(res => res.json())
    .then(data => {
        ...

and then create your types

        ...
        var Gender = t.enums(data);
        var Person = t.struct({ name: t.String, gender: Gender });
        // do something with Person
    })
    .catch(err => alert(err));

This assumes you're using fetch but it will work similarly with jQuery.getJson or whatever other http client you prefer.

volkanunsal commented 7 years ago

You can transform a JSON object into type descriptions with the library above. You can also roll your own type factory, but tcomb-json-schema worked well for me. You need this because you can't include functions in a JSON payload, unless defined as string which you can then eval() on the clientside, but I wouldn't recommend that approach.

dvwright commented 7 years ago

Hi, thank you for the responses, the project I was using this for is on hold, I will revisit again when I get a chance. Closing for now