简体   繁体   中英

Mutations using Relay Environment

I'm using Relay with React Native and have a problem during login & logout.

After login or logout, Relay keeps the store from the previous user. To solve this I use Relay.Renderer and Relay.Environment . As in, in each Renderer I put singleton object of Environment .

The problem is that I previously did a mutation on object of Relay.Store , as in Relay.Store.commitUpdate(new CreateProfile(), callback) .

Now it doesn't work. I guess this is because Relay.Store doesn't know anything about server endpoints. But Relay.Environment does.

And now I'm using something like this this.props.relay.commitUpdate(new CreateProfile(), callback) . It works pretty well when the parent component is wrapped as Relay.Container , so it has relay object in props.

But what should I do in components which are not Relay.Containers and don't have Relay object in props?

Relay.Store is a globally accessible singleton instance of Relay.Environment and Relay.Store.commitUpdate() updates data in that global environment. But since you're using your own instance of Relay.Environment , to update it you need to use this.props.relay.commitUpdate() , as you noted. This updates the environment the container was rendered with.

If need to make mutations from child components of containers , that are not wrapped in a Relay.Container , there are two ways to do that. You could simply pass the relay prop to them, so in the render function of your container you would have:

<Child relay={this.props.relay} />

However, since those plain components are not in a Relay container, they don't currently need to know anything about Relay. If you want to keep them that way, you could write the method that does the update in your container component like this:

onCreateProfile = () => {
  this.props.relay.commitUpdate(new CreateProfile());
};

and only pass a callback to your child component in render :

<Child onCreateProfile={this.onCreateProfile} />

If you need to make a mutation from a component that does not have a Relay.Container above it in the component hierarchy at all, you could create the Relay.Environment in a shared root component higher up and pass it down using props (or pass a callback using the strategy shown above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM