I
I
Insolation2018-05-13 18:52:40
React
Insolation, 2018-05-13 18:52:40

Where is the best place to store data?

Hello.
I have an application that will display a list of products and click on a product to display data about it. I have 2 suggestions how to store product data (they come via API).
1. Make a class (simple, not a component) of the service (it will be a Singleton) in which we will send a request, store data, and methods . And only then use this class for all other components. 2. Or do the whole thing in the component, saving the data in the local state and push the data further through the props to the descendants. Tell me from experience how best to do it? PS I know that it's easier to use , but for now I want to do without it. get set
Redux

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-05-13
@Insolation

1. Forget about such approaches in React . An extra useless entity. It is better to put the API requests themselves into a separate module .
2. If you use the bare React API , then this is the surest way, since when the state changes , the component and its descendants will be updated.

import React, { Component } from 'react';
import { Child } from './Child';
import { getSomeData } from './api';

class Parent extends Component {
  state = {
    data: [],
  };

  componentDidMount() {
    getSomeData.then(data => this.setState({ data });
  }

  render() {
    return <Child data={this.state.data} />;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question