1

I have a GetData.js component that gets API data and sets it to an array. I want to access that array data in multiple other components and manipulate it in multiple different ways.

For example, I want to be able to do something like this:

import APIdata from './GetData';

var data = APIdata.object;

var result = [];

if (data) {
  for (var i = 0; i < data.length; i++) {
    if (data.form_values["6f71"] === "KeyWord") {
      result.push(data)
    }
  }
}
2
  • You can wrap that data in a parent Component and pass it down as a property when needed. Commented Jul 22, 2018 at 3:53
  • Could you please demonstrate how i would do that? Sorry, i am new to react.@LaneTerry Commented Jul 22, 2018 at 3:59

1 Answer 1

1

You're looking at a fairly straightforward use of container components, props, and state.

Here's a contrived example:

import React, {Component} from 'react';
import OtherComponent1 from './OtherComponent1';
import OtherComponent2 from './OtherComponent2';

class GetDataComponent extends Component {
  constructor() {
    super(props);
    this.state = {
      data: []
    }
  }

  fetchMyData() {
    const resultingArray = ...
    this.setState({data: resultingArray});
  }

  componentDidMount() {
    this.fetchMyData();
  }

  render() {
    return (
      <div>
        <OtherComponent1 someArrayProp={this.state.data}/>
        <OtherComponent2 differentArrayProp={this.state.data}/>
      </div>
    );
  }
}

export default App;

import React, {Component} from 'react';
import PropTypes from 'prop-types';

class OtherComponent1 extends Component {
  render() {
    return (
      <div>
        The someArrayProp: {this.props.someArrayProp}
      </div>
    );
  }
}

OtherComponent1.propTypes = {
  someArrayProp: PropTypes.array;
}

export default App;

import React, {Component} from 'react';
import PropTypes from 'prop-types';

const OtherComponent2 = (props) => (
  <div>
    The differentArrayProp: {props.differentArrayProp}
  </div>
);

OtherComponent2.propTypes = {
  differentArrayProp: PropTypes.array;
}

export default App;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.