user2492364
user2492364

Reputation: 6703

when use redux, can I call api in container component?

I am very confused recently.
When I write redux, if I have to call api ,I will put an action to update reducer, the component just render the data from props

But recently I see my coworker just call api in container component and then update the component state.
He says if your data do not need to share with other component, you can call api in component, so you don't have to write so many code in actions and reducers.

I thought this is very convenient. For example: If I have a feature : When user click the button, I have to send an email.
This feature do not need to update store by reducer, just have to alert "send success"

So I can write this code in container component:

async onClick() {
  // 1. call api
  const {error, response} = await sendMail({email: this.state.email});
  if (response){    
    // 2. alert success
    this.setState({
      modal: {
        show: true,
      }
    });
  }
}

But I don't know if this match redux's principle.
Can I call api directly in component if the state do not need to share with other component??

Upvotes: 4

Views: 1148

Answers (2)

Damien Leroux
Damien Leroux

Reputation: 11693

You can call api from dispatched actions or from React components: it is your choice to make. There is no mandatory rules here and it depends on what you want to do with your components:

When to use React states:

  • It is better to have smart component handling their own state because it ease the integration in external projects. Having a component that uses Redux means a project needs to add the requires reducers to use the component.
  • If a component handles information not required by any other components, use React state. It is often the case for information related to UI state.

When using Redux reduces:

  • If you need to test your component, prefer Redux because you'll be able to connect "test actions" to your component when testing them.
  • If you need to share a bundle of data through components, prefer Redux to mutualise information.

This question has been treated by Gaeron on Redux github repository if you want to have a look. He explains:

Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft. Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local). The rule of thumb is: do whatever is less awkward.

Upvotes: 7

魔王K
魔王K

Reputation: 30

I suggest you have a look at classux

Upvotes: -3

Related Questions