javascript.iscool.pl javascript.iscool.pl - 5 months ago 10
Javascript Question

Relay Playground - how get it to work?

I changed ("hello" to "text" in schema) in the Relay Playground like this:

SCHEMA:

import {
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLInt
} from 'graphql';

const GREETINGS =
{text: 'Hello world 1'}
;

const GreetingsType = new GraphQLObjectType({
name: 'Greetings',
fields: () => ({
text: {type: GraphQLString}
})
});

export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: () => ({
greetings: {
type: GreetingsType,
resolve: () => GREETINGS
}
})
})
});


CODE:

class HelloApp extends React.Component {
render() {
const {hello} = this.props.greetings;
return <h1>test: {hello}</h1>;
}
}

HelloApp = Relay.createContainer(HelloApp, {
fragments: {
greetings: () => Relay.QL`
fragment on Greetings {
text
}
`,
}
});

class HelloRoute extends Relay.Route {
static routeName = 'Hello';
static queries = {
greetings: (Component) => Relay.QL`
query GreetingsQuery {
greetings {
${Component.getFragment('greetings')},
},
}
`,
};
}

ReactDOM.render(
<Relay.RootContainer Component={HelloApp} route={new HelloRoute()} />,
mountNode
);


But it doesn't work and I get no error messages. Nothing is rendering. When I change the "text" back into "hello" back it works again. Why? Looks like the schema is hardcoded?

EDIT:

This works (I know why):

const sm = this.props.greetings;
return <h1>test: {sm.text}</h1>;


This works too:

const {text} = this.props.greetings;
return <h1>test: {text}</h1>;


but this below not works (and I don't know why if the one above works, why not works with custom variable name? what is specific with "text" variable name above?):

const {sm} = this.props.greetings;
return <h1>test: {sm}</h1>;


SOLVED:

ES6 feature. The curly braces should contain property. This is why
text
works. Thanks @Vince Ning.

Answer

In your React app, you are destructuring you your props like so:

const {hello} = this.props.greetings;

Since greetings is a JSON object, you only retrieved the hello property of that object, not the rest of it. In order to get correct data, you can either get the entire object by removing the {} around hello in that statement:

const hello = this.props.greetings;
console.log(hello.text); // Hello world 1

Or you can change the hello inside the {} to text to retrieve that specific property like so:

const {text} = this.props.greetings;
console.log(text); // Hello world 1

Hope this helps!

Comments